通过在python中输入来将多行写入文本文件?

时间:2014-12-06 09:43:48

标签: python python-2.7 input text-files raw-input

Iam尝试编写一个python脚本,让我直接将C代码写入文本文件,并将其扩展名更改为“.c”,而无需手动创建。这就是我到目前为止所做的..

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 个答案:

答案 0 :(得分:0)

而不是一次调用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.