'how can i loop to read, load and parse files in python
I need to take user input for no.of files, suppose user enters 'n' then a loop should run to read , load the files. For eg - incase of 4 files, we do this where file name is saved as- name(prime number) ...but i want to use loop incase the no.of file increases
with open ('name0.json', 'r') as f1:
data1= json.load(f1)
with open ('name2.json', 'r') as f2:
data2= json.load(f2)
with open ('name4.json', 'r') as f3:
data3= json.load(f3)
with open ('name6.json', 'r') as f4:
data4= json.load(f4)
Solution 1:[1]
This code reads the given amount of files into a list for further processing . It only read all files with a even number.
import json
user_input = None
while type(user_input) != type(int):
user_input = input("Please enter a number of files to read: ")
files = []
for index in range(0, int(user_input)+1, 2):
with open(f"file{index}.json", "r") as file:
files.append(json.load(file))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gerda die gandalfziege |
