Writing multiple lines to a textfile by taking inp

2019-08-19 03:04发布

Iam trying to write a python script that will let me write C code directly to a textfile and change its extension to ".c" without me creating one manually. This is what i did so far..

import time as t
from os import path

def create_C(dest):

    date=t.localtime(t.time())                #getting current system date
    name=raw_input("Enter file name:")+"%d_%d_%d"%(date[0],date[1],date[2])+".c"
                                                            #User enters the filename 

    if not(path.isfile(dest+name)):           #checks if the file already exists
        f=open(dest+name,"w")
        f.write(raw_input("Start Writting:\n"))
        f.close()
    if __name__=='__main__':
        destination='C:\\Users\\Dell\\Desktop\\Puru\
\\python\\intermediate\\createCfile\\'
        create_C(destination)
        raw_input("done")

However this writes only 1 line. How can i get it to write multiple lines?

1条回答
虎瘦雄心在
2楼-- · 2019-08-19 03:34

Instead of calling raw_input once:

f.write(raw_input('Start writing'))

You can call raw_input until an empty string is inserted:

file_content = '\n'.join(iter(raw_input, ''))
f.write(file_content)

Little clearer:

file_lines = iter(raw_input, '') # Get lines as input until an empty line.
file_content = '\n'.join(file_lines) # Join the file lines to one string, seperated by new-line.
查看更多
登录 后发表回答