Writing multiple lines to a textfile by taking input in python?

老子叫甜甜 提交于 2019-12-25 01:42:45

问题


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:


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.


来源:https://stackoverflow.com/questions/27330316/writing-multiple-lines-to-a-textfile-by-taking-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!