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

reading multiple files in a directory as python list

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.

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

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().

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