【问题标题】:Writing multiple lines to a textfile by taking input in python?通过在 python 中输入将多行写入文本文件?
【发布时间】:2014-12-06 09:43:47
【问题描述】:

我正在尝试编写一个 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 行。 我怎样才能让它写多行?

【问题讨论】:

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


    【解决方案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, ''))
    • 我添加了一个解释。 @PurusharthDwivedi
    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2017-05-31
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多