python文件式运行怎么输入多行文字_通过在python中输入将多行写入文本文件?

1586010002-jmsa.png

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值