2016-11-04 101 views
0
count = 0 
path = input("Please enter the directory you want to get the files from. -> ") 
for filename in glob.glob(os.path.join(path, '*.ppm')): 
    file_obj = open(filename, "r", encoding="utf-8") 
    list_of_files.append(file_obj) 
    count += 1 

这个代码几乎扫描给定目录的用户,并打开该目录中的所有.ppm文件。当它逐个打开它时,它将(类 - '_io.TextIOWrapper')附加到列表中。Python - 如何通过名称打开输入文件

一个人如何按照名称打开文件?

Ex。 image1.ppm,image2.ppm,image3.ppm,image4.ppm在我的目录中。

的代码读取和顺序打开文件:

image2.ppm

image4.ppm

image1.ppm

image3.ppm

回答

1

您可以使用sorted()超过glob.glob(os.path.join(path, '*.ppm'))

count = 0 
path = input("Please enter the directory you want to get the files from. -> ") 
for filename in sorted(glob.glob(os.path.join(path, '*.ppm'))): 
    file_obj = open(filename, "r", encoding="utf-8") 
    list_of_files.append(file_obj) 
    count += 1