Search code examples
pythonlisttext

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')

Solution

  • 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