通过在python中输入将多行写入文本文件?
问题描述:
Iam试图编写一个python脚本,它可以让我直接将C代码写入文本文件并将其扩展名更改为“.c”,而无需手动创建。这是我到目前为止..通过在python中输入将多行写入文本文件?
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")
但是,这只写1行。 我怎样才能得到它写多行?
答
而不是调用的raw_input一次:
f.write(raw_input('Start writing'))
你可以调用的raw_input,直到一个空字符串插入:
file_content = '\n'.join(iter(raw_input, ''))
f.write(file_content)
略知一二:
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.
谢谢,你能还解释一点点在这里发生** file_content ='\ n'.join(iter(raw_input,''))** – purudpd 2014-12-06 10:51:44
我添加了一个解释。 @PurusharthDwivedi – 2014-12-06 11:40:54