Akhil
Akhil

Reputation: 77

How to generate arrays of text files serially?

aTxt folder has 3000 text files. My code reads these .txt files in a random order like(1.txt,10.txt,1000.txt,...). How can I read these text files serially (like first it read 1.txt then 2.txt and so on upto 3000.txt) and append these text files to an array?

from pickle import dump
import glob
textlist = []
textfiles = glob.glob('D:/qrt/aTxt/*.txt')
for x in textfiles:
    x1 = open(x, 'r')
    x2 = x1.read()
    textlist.append(x2)
    x1.close()
dump(textlist, open('textlists.pkl', 'wb'))

Upvotes: 0

Views: 22

Answers (1)

Guillaume
Guillaume

Reputation: 6009

If you mean lexical order you can simply sort the list of filepath that you obtained from glob using builtin function sorted()

from pickle import dump
import glob
textlist = []
textfiles = glob.glob('D:/qrt/aTxt/*.txt')
for filepath in sorted(textfiles):
    with open(filepath , 'rt') as finput:
        content = finput.read()
        textlist.append(content)

dump(textlist, open('textlists.pkl', 'wb'))

Upvotes: 1

Related Questions