首先使用发电机
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变量来形成文件名的建议也是非常好的