简体   繁体   中英

How to read multiple text files into arrays?

I have multiple text files, each containing several columns. I need to read each file into an array in python, called RDF. The point is that I used to read one file into one array as following:

RDF_1 = numpy.loadtxt("filename_1.txt", skiprows=205, usecols=(1,), unpak=True)

How to create a loop in python such that it reads more than one file into their corresponding arrays like this:

for i in range(100):
    RDF_i =  numpy.loadtxt("filename_"+str(i)+".txt", skiprows=205, usecols=(1,), unpak=True)

You can use dictionaries as a proper way:

files_mapping = dict()
for i in range(100):
    files_mapping[f'RDF_{i}'] = numpy.loadtxt(f"filename_{i}.txt", skiprows=205, usecols=(1,), unpak=True)

But if for some unknown reasons you really need to dynamically create variables then you can use exec :

for i in range(100):
    exac(f'RDF_{i} = numpy.loadtxt(f"filename_{i}.txt", skiprows=205, usecols=(1,), unpak=True)'

And another possible way is using locals :

for i in range(100):
    locals()[f'RDF_{i}'] = numpy.loadtxt(f"filename_{i}.txt", skiprows=205, usecols=(1,), unpak=True)

You need to avoid using two last options in real code because it's a direct way to spawning hard-to-find bugs.

I found a way to do it. I use two dimensional arrys after importing numpy library.

However, I had to zero the arrays before filling them out with data because python had already filled them out with random values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM