How to get strings from a group of files in order in python? -


i have 2 directories, both files [0-100]*.txt. i'm trying first number these files , put them 2 different arrays - 1 one directory, , 1 other directory.

however, need python them in order. doesn't have 0-100, has consistent across both directories, array_1[0] n'th file in directory, while array_2[0] n'th file in other directory. current method reads them in random order. how can go doing this?

current code:

os.chdir("/first/directory") file in glob.glob("*.txt"):         open(file) f:                 line in f:                         data = line.split()                         array_1.append(float(data[0])) os.chdir("/second/directory") file in glob.glob("*.txt"):         open(file) f:                 line in f:                         data = line.split()                         array_2.append(float(data[0])) 

your code getting first number of each line of each file, however, written, question requests first number of each file. can this:

for filename in glob.glob("/first/directory/*.txt"):     open(filename) f:         array_1.append(float(next(f).split()[0])) 

regarding ordering of filenames, need clarify whether files 0.txt through 100.txt exist one-for-one in both directories. if do, glob() should return same lists. if have concerns sort file list:

for filename in sorted(glob('/first/directory/*.txt')):     .... 

or iterate on files number:

max_file=100  array_1 = [] array_2 = []  in range(max_file+1):     open('/first/directory/{}.txt'.format(i)) f:         array_1.append(float(next(f).split()[0]))     open('/second/directory/{}.txt'.format(i)) f:         array_2.append(float(next(f).split()[0])) 

Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -