【问题标题】:How to read files with Incremental file name in python? [closed]如何在python中读取具有增量文件名的文件? [关闭]
【发布时间】:2017-06-13 03:11:43
【问题描述】:

我有多个文件,名称如 file00001、.....、file00111、.....file01555 等。我想在 python 中以增量方式阅读它们。最好的方法是什么?最初我使用创建时间以增量顺序读取它们,但不幸的是,当我将这些文件传输到另一台计算机时,文件的创建时间和它们的名称不再匹配。所以这段代码不起作用。我的代码是这样的。其中一些命令是特定于软件的,例如 pymol、cmd,但我认为其余代码非常通用。如果没有正确提出问题,我很抱歉,但我对 python 很陌生,编程不是我的专业。它帮助我更有效地完成工作,这就是我尝试它的原因。

My code

谢谢 迪拉杰

【问题讨论】:

标签: python list file


【解决方案1】:

如果您想立即对文件执行某些操作,请继续:

def get_files():
    MAX_FILE_NUM = 100 #change
    fmat = lambda x: '{:05}'.format(x)

    for i in range(1, MAX_FILE_NUM + 1):
        path = 'file' + fmat(i)
        new_file = open(path, 'r')
        # Do something with the new_file object...

get_files()

如果您希望能够从函数中一次获取一个文件:

def get_files():
    MAX_FILE_NUM = 100 #change
    fmat = lambda x: '{:05}'.format(x)
    for i in range(1, MAX_FILE_NUM + 1):
        path = 'file' + fmat(i)
        new_file = open(path, 'r')
        yield new_file

files = get_files()

print(next(files)) #<file object 1>
print(next(files)) #<file object 2>

【讨论】:

    【解决方案2】:

    你应该试试这样的

    import glob
    path = ''#your path
    files = glob.glob(path)
    for name in files:
        with open(name) as f:
                for line in f:
                    print(line.split())
    

    您可以阅读有关 glob 的更多信息并了解如何针对您的问题进行调整 glob

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-30
      • 2022-06-10
      • 2022-12-06
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多