简体   繁体   中英

Read through files in a folder

I have a folder with files of certain extension name, eg : 'LRZ_OA_12115.txt'. I have hundreds of files with these names. The following is the task: i) I want to get access to each of these files in the numeric order. For examples, I will like to have LRZ_OA_12115 before LRZ_OA_12116. ii) I want to get access of and read this part : 12115 ( not the alphabets) of each files in the folder.

I will appreciate any answer.

Thanks.

Do this:

 import os, glob
 files = sorted(glob.glob(path + '*.txt'), key=os.path.basename)

For numerically you can do this:

 files = sorted(glob.glob('*.txt'), key=lambda name: int(os.path.splitext(name)[0]))

My proposal:

import os
the_dir = "/path/to/your/files"

print(sorted(os.listdir(the_dir),key = lambda x: int(os.path.splitext(x)[0]) if os.path.splitext(x)[0].isdigit() else 0))

It sorts directory listing according to the numerical value of the name part (without extension), checking that this part is numerical to avoid exception when converting to integer (other names - if there are some - are left at the start, and not sorted)

You can use os and os.path functions from the Python standard library.

for filename in sorted(os.listdir('<your-directory>')):
    name, _ = os.path.splitext(filename)
    # do something with name

As Jean-François Fabre notes, this gives lexicographic order (12115 before 12116, but 2 before 10) instead of strictly numeric order. If you need the latter, then modify the code like this:

sort_key = lambda x: int(os.path.splitext(x)[0]) if os.path.splitext(x)[0].isdigit() else 0
for filename in sorted(os.listdir('<your-directory>'), key=sort_key):
    ...

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