加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python – 为列表中的每个项创建一个文件

发布时间:2020-12-20 11:34:45 所属栏目:Python 来源:网络整理
导读:我正在尝试使用 python为列表中的每个项目创建单独的文本文件. List = open('/home/user/Documents/TestList.txt').readlines()List2 = [s + ' time' for s in List]for item in List2 open('/home/user/Documents/%s.txt','w') % (item) 此代码应从目标文本
我正在尝试使用 python为列表中的每个项目创建单独的文本文件.

List = open('/home/user/Documents/TestList.txt').readlines()
List2 = [s + ' time' for s in List]
for item in List2 open('/home/user/Documents/%s.txt','w') % (item)

此代码应从目标文本文件生成列表.使用第一个列表中的字符串和一些附件生成第二个列表(在这种情况下,将“时间”添加到结尾).我的第三行是我遇到问题的地方.我想为新列表中的每个项目创建一个单独的文本文件,其中文本文件的名称是该列表项的字符串.示例:如果我的第一个列表项是“健康时间”而我的第二个列表项是“食物时间”,则会生成名为“healthy time.txt”和“food time.txt”的文本文件.

看起来我遇到了open命令的问题,但我已经广泛搜索并且没有发现在列表的上下文中使用open的问题.

解决方法

首先使用发电机

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变量来形成文件名的建议也是非常好的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读