【问题标题】:Python - How to open input files by namePython - 如何按名称打开输入文件
【发布时间】:2016-11-04 06:31:55
【问题描述】:
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 文件。当它一一打开它们时,它会将 (class - '_io.TextIOWrapper') 附加到一个列表中。

人们如何按名称按顺序打开文件?

例如。 image1.ppm、image2.ppm、image3.ppm、image4.ppm 在我的目录中。

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

image2.ppm

image4.ppm

image1.ppm

image3.ppm

【问题讨论】:

    标签: python file input 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
    

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 2023-02-09
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多