Code4Days
Code4Days

Reputation: 141

Python Change How Reads Numbered Files

I have many files labeled starting with the string "example" and ending with a number (in which the order matters). I am renaming all of the files (in order), and instead of reading the files in order of example1, example2, example3, ..., example150, it is reading the files in order of example1, example10, example100, example 101, example 102, ..., and repeating this process. How can I change it to read the files in sequential order? Thanks!

Upvotes: 0

Views: 71

Answers (3)

f.rodrigues
f.rodrigues

Reputation: 3587

files = ['example1.txt','example2.txt', 'example10.txt','example11.txt', 'example100.txt', 'example101.txt', 'example102.txt']

def sort_numericly(file_list,prefix,sufix):
    new_file_list = []
    for f in file_list:
        f = f.strip(prefix).strip(sufix)
        new_file_list.append(int(f))
    return [prefix+ str(f) + sufixfor f in sorted(new_file_list)]

print sorted(files)
print sort_numericly(files,'example','.txt')

Output:

['example1.txt', 'example10.txt', 'example100.txt', 'example101.txt', 'example102.txt', 'example11.txt', 'example2.txt']
['example1.txt', 'example2.txt', 'example10.txt', 'example11.txt', 'example100.txt', 'example101.txt', 'example102.txt']

Upvotes: 0

Dov Grobgeld
Dov Grobgeld

Reputation: 4983

Sort takes a key argument that can be used to set the sorting key. For your problem you may get rid of all the text, and then use int() to turn the string into your integer sort key:

for files in sorted(files, 
                    key=lambda f: int(f.replace('example','').replace('.txt',''))):
    # process the file

Upvotes: 1

martijnn2008
martijnn2008

Reputation: 3640

Something like this?

n = .. # amount of files 
for i in range(0, n) :
    f = open("example" + str(i), "r")
    # do something with your file
    f.close()

Upvotes: 1

Related Questions