通过在python中输入将多行写入文本文件? [英] Writing multiple lines to a textfile by taking input in python?

查看:1341
本文介绍了通过在python中输入将多行写入文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

但是,这仅写入1行. 我怎样才能写多行?

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

推荐答案

而不是一次调用raw_input:

Instead of calling raw_input once:

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

您可以调用raw_input,直到插入空字符串为止:

You can call raw_input until an empty string is inserted:

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.

这篇关于通过在python中输入将多行写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆