【问题标题】:iterating through specific files in folder with name matching pattern in python在python中使用名称匹配模式遍历文件夹中的特定文件
【发布时间】:2021-11-30 09:51:18
【问题描述】:

我有一个文件夹,里面有很多不同名称的 csv 文件。 我只想处理名称仅由数字组成的文件, 虽然我没有文件标题中数字范围的信息。

例如,我有 ['123.csv', 'not.csv', '75839.csv', '2.csv', 'bad.csv', '23bad8.csv'] 我只想和['123.csv', '75839.csv', '2.csv']一起工作

我尝试了以下代码:

for f in file_list:
    if f.startwith('1' or '2' or '3' ..... or '9'):
        # do something

但如果文件名以数字开头但稍后仍包含字母或其他符号,这不会有问题。

【问题讨论】:

    标签: python csv filenames


    【解决方案1】:

    其中一种方法:

    import re
    lst_of_files = ['temo1.csv', '12321.csv', '123123.csv', 'fdao123.csv', '12312asdv.csv', '123otk123.csv', '123.txt', '876.csv']
    for f in lst_of_files:
        if re.search(r'^[0-9]+.csv', f):
            print (f)
    

    输出:

    12321.csv
    123123.csv
    876.csv
    

    【讨论】:

      【解决方案2】:

      您可以使用Regex 执行以下操作:

      import re
      lst_of_files = ['temo1.csv', '12321.csv', '123123.csv', 'fdao123.csv', '12312asdv.csv', '123otk123.csv', '123.txt']
      pattern = re.compile('^[0-9]+.csv')
      newlst = [re.findall(pattern, filename) for filename in lst_of_files if len(re.findall(pattern, filename)) > 0]
      print(newlst)
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        file_list = ["123.csv", "not.csv", "75839.csv", "2.csv", "bad.csv", "23bad8.csv"]
        for f in file_list:
            name, ext = f.rsplit(".", 1)    # split at the rightmost dot
            if name.isnumeric():
                print(f)
        

        输出是

        123.csv
        75839.csv
        2.csv
        

        【讨论】:

          猜你喜欢
          • 2020-05-03
          • 2017-01-03
          • 2018-08-13
          • 1970-01-01
          • 2019-01-21
          • 2021-01-19
          • 1970-01-01
          • 2021-11-06
          • 2021-05-24
          相关资源
          最近更新 更多