简体   繁体   English

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

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

I have a list of file path that looks like the following (but longer as it goes up to test10.txt:我有一个文件路径列表,如下所示(但随着 test10.txt 的增加而更长:

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

I also have a code that opens a file from a file path however it only takes strings, not lists of strings.我还有一个从文件路径打开文件的代码,但它只需要字符串,而不是字符串列表。 I've tried the following but it does not work:我已经尝试了以下但它不起作用:

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

Again this does not work as it requires a string not a list of strings.这再次不起作用,因为它需要一个字符串而不是字符串列表。

This continues to the rest of my code which isn't important.这继续到我的其余代码,这并不重要。 I just want to know how to get the code to open each file from the list of file paths such that I can use what's written in them.我只想知道如何获取代码以从文件路径列表中打开每个文件,以便我可以使用其中写入的内容。 Is there a way to do this?有没有办法做到这一点?

I think you may be misunderstanding how for loops work in python.我认为您可能误解了 for 循环在 Python 中的工作方式。 They are actually more aptly named "for each loops".它们实际上被更恰当地命名为“for each loops”。 Another way to put this into english terms would be to say "for each item in testlist, set i equal to the current item, and then run this block of code."另一种将其转化为英语术语的方法是说“对于测试列表中的每个项目,将 i 设置为当前项目,然后运行此代码块。”

That means that the variable i will be equal to each element in testlist, sequentially, for each iteration.这意味着对于每次迭代,变量 i 将依次等于 testlist 中的每个元素。 IE it will first be the string '/Users/myname/Downloads/files_list/test1.txt', then '/Users/myname/Downloads/files_list/test2.txt', and so on. IE 它将首先是字符串“/Users/myname/Downloads/files_list/test1.txt”,然后是“/Users/myname/Downloads/files_list/test2.txt”,依此类推。 Does this answer your question?这回答了你的问题了吗?

This is probably what you want,这大概就是你想要的

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