python打开文件并创建列表,Python – 为列表中的每个项创建一个文件

首先使用发电机

List = open("/path/to/file") #no need to call readlines ( a filehandle is naturally a generator of lines)

List2 = (s.strip() + ' time' for s in List) #calling strip will remove any extra whitespace(like newlines)

这会导致延迟评估,因此您不会循环,循环和循环等

然后修复你的行(这是导致程序错误的实际问题)

for item in List2:

open('/home/user/Documents/%s.txt'%(item,),'w')

# ^this was your actual problem,the rest is just code improvements

所以你的整个代码变成了

List = open("/path/to/file") #no need to call readlines ( a filehandle is naturally a generator of lines)

List2 = (s.strip() + ' time' for s in List)

for item in List2: #this is the only time you are actually looping through the list

open('/home/user/Documents/%s.txt'%(item,'w')

现在你只循环遍历列表一次而不是3次

使用filePath变量来形成文件名的建议也是非常好的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值