简体   繁体   中英

How can I add a text from a list to open a file?

I'd like to open a file but I don't want to write the name of the file everytime, that's why I want to create a list and then choose the element by putting 0,1,2... I don't understand how it works, I tried to do this but it doesn't work. Can anyone help me?

L=["file1","file2","file3"]

file = open('D:/folder/'L[0]'.txt', 'r')

I think what your looking for here is string formatting or f-strings.

Assuming you'd like to read information from a file with the path D:/folder/file1.txt' you should use f strings to format the correct path as such:

file = open(f'D:/folder/{L[0]}.txt', 'r')

You can use this idea to iterate through your list and read the individual files and do what you need to do with it:

for filename in L:
    file = open(f'D:/folder/{filename}.txt', 'r')
    # Do operations for each file here

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