Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading