【问题标题】:Python - Creating a file for each item in a listPython - 为列表中的每个项目创建一个文件
【发布时间】:2014-04-04 16:50:23
【问题描述】:

我正在尝试使用 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)

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

看来我在使用 open 命令时遇到了问题,但我进行了广泛搜索,但没有发现任何关于在列表上下文中使用 open 的信息。

【问题讨论】:

  • 您会遇到哪些问题?错误信息?

标签: python list filenames


【解决方案1】:

首先使用生成器

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

【讨论】:

    【解决方案2】:

    将您的标记化移动到文件路径字符串。现在它不在open 的调用范围内。

    for item in List2:
        filePath = '/home/user/Documents/%s.txt' % (item)
        open(filePath, 'w')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 2020-09-24
      • 1970-01-01
      • 2017-11-18
      • 2021-10-10
      • 1970-01-01
      • 2019-10-17
      • 2012-10-25
      相关资源
      最近更新 更多