简体   繁体   中英

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:

   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. They are actually more aptly named "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."

That means that the variable i will be equal to each element in testlist, sequentially, for each iteration. 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. 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() 
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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