Home > database >  Python: How to read variable file names in a loop
Python: How to read variable file names in a loop

Time:03-05

I have various JSON files on my drive that I would like to process in a loop, but how can I read them in a loop?

Basically I have a list where all filenames are included and all files are also in one folder.

The objective is to create lists out the json files in a loop.

TestList = ["cats", "dogs"]

for i in TestList:
    with open ("{i}.json") as {i}_file:
               print({i}_file)

Unfortunately I get syntax errors no matter how I try it.

Thank you so much in advance for your support!

CodePudding user response:

Use:

TestList = ["cats", "dogs"]

for i in TestList:
    with open(f"{i}.json") as fp:
        print(fp.read())

First, if you use "{i}.json", add the prefix f to define this string as f-strings.

Then your variable {i}_file can't be dynamically evaluated to create the variables cats_file and dogs_file. You have to use a static name.

  • Related