繁体   English   中英

如何从文件路径列表中打开文件

[英]How to open files from a list of file paths

我有一个文件路径列表,如下所示(但随着 test10.txt 的增加而更长:

   testlist = ['/Users/myname/Downloads/files_list/test1.txt', '/Users/myname/Downloads/files_list/test2.txt', '/Users/myname/Downloads/files_list/test3.txt']

我还有一个从文件路径打开文件的代码,但它只需要字符串,而不是字符串列表。 我已经尝试了以下但它不起作用:

for i in testlist:        
    with open(testlist, "r") as flp:
        file_list = flp.readlines()  
        fp = [x.strip() for x in file_list]

这再次不起作用,因为它需要一个字符串而不是字符串列表。

这继续到我的其余代码,这并不重要。 我只想知道如何获取代码以从文件路径列表中打开每个文件,以便我可以使用其中写入的内容。 有没有办法做到这一点?

我认为您可能误解了 for 循环在 Python 中的工作方式。 它们实际上被更恰当地命名为“for each loops”。 另一种将其转化为英语术语的方法是说“对于测试列表中的每个项目,将 i 设置为当前项目,然后运行此代码块。”

这意味着对于每次迭代,变量 i 将依次等于 testlist 中的每个元素。 IE 它将首先是字符串“/Users/myname/Downloads/files_list/test1.txt”,然后是“/Users/myname/Downloads/files_list/test2.txt”,依此类推。 这回答了你的问题了吗?

这大概就是你想要的

testlist = ['/Users/myname/Downloads/files_list/test1.txt', '/Users/myname/Downloads/files_list/test2.txt', '/Users/myname/Downloads/files_list/test3.txt']

# iterating over the list 
for i in testlist:        
  with open(i, "r") as file:
    line = file.readlines() 
    ....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM