[英]Write output of for loop to multiple files with same filename as input file
I have a list of filenames in the file filenames.txt. 我在文件filenames.txt中有一个文件名列表。 I am opening all the files one by one, and want to write the result of some operation to a different directory but with the same file name.
我正在一个一个地打开所有文件,并希望将某些操作的结果写入具有相同文件名的其他目录。 So far, I tried this, but this won't work.
到目前为止,我已经尝试过了,但是这行不通。 Any help?
有什么帮助吗?
with open("/home/morty/filenames.txt","r") as f:
names = [name.strip() for name in f]
for name in names:
save=open("/home/morty/dir/%name" %name,"w")
save.write(---some operation---)
My question is similar to this, but I don't want the files named by count/enumerate. 我的问题与此类似,但是我不希望按count / enumerate命名的文件。 I want the names to be the same as the input file name: Write output of for loop to multiple files
我希望名称与输入文件名相同: 将for循环的输出写入多个文件
Your format statement is incorrect. 您的格式声明不正确。 It should be
"/home/morty/dir/%s" %name
它应该是
"/home/morty/dir/%s" %name
But when you want to join a directory name with a file name, best is to use os.path.join
like this: 但是,当您想将目录名与文件名结合在一起时,最好使用
os.path.join
如下所示:
for name in names:
with open(os.path.join("/home/morty/dir",name),"w") as save:
save.write(---some operation---)
(and a with
context block to make sure that the file is closed when done) (以及一个
with
上下文块,以确保完成后关闭文件)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.