I am trying to read multiple files in my directory as python list. The txt files contains list of IDs.
eg., H104.txt
CZ104
Cz509
T3G63
Im sharing the script I wrote,
files = ["H104.txt","H905.txt","H920B1.txt","T636.txt"]
# shell script for getting file list
# ls | tr ' ' ',' | tr '\n' ',' | sed -r 's/[^,]+/"&"/g'
f = ["H104","H905","H920B1","T636"]
i = 0
while i < len(f):
for filename in files:
with open(filename, 'r') as onefile:
f[i] = onefile.readlines()
i += 1
print(H104)
I want to read these multiple files using their respective file names as a variable. The above script gives me Nameerror NameError: name 'H104' is not defined.
The output I want,
["CZ104","Cz509","T3G63"]
>Solution :
I want to read these multiple files using their respective file names as a variable.
It’s a bit hard to tell, but I think you want a dictionary here. For example:
# Fill the dict: keys are filenames, values are lists of lines.
file_lines = {}
for filename in files:
with open(filename, 'rt') as file:
lines = [line.rstrip('\n') for line in file.readlines()]
file_lines[filename] = lines
# Access each file by its key in the dict.
print(file_lines['H104.txt'])
If you don’t mind that each line ends with a \n newline character, you can also simplify the reading down to lines = file.readlines().