【问题标题】:Processing filenames in Python在 Python 中处理文件名
【发布时间】:2019-05-22 22:48:09
【问题描述】:

我编写了一个函数来从我的原始数据文件中去除双空格:

def fixDat(file):
    '''
    Removes extra spaces in the data files. Replaces original file with new
    and renames original to "...._original.dat".
    '''
    import os

    import re
    with open(file+'.dat', 'r') as infile:
        with open(file+'_fixed.dat', 'w') as outfile:
            lines = infile.readlines()
            for line in lines:
                fixed = re.sub("\s\s+" , " ", line)
                outfile.write(fixed)

    os.rename(file+'.dat', file+'_original.dat')
    os.rename(file+'_fixed.dat', file+'.dat')

我的文件夹中有 19 个文件需要使用此函数处理,但我不确定如何解析文件名并将它们传递给函数。类似的东西

for filename in folder:
    fixDat(filename)

但是我如何在 Python 中编码 filenamefolder

【问题讨论】:

    标签: python file directory filenames


    【解决方案1】:

    如果我理解正确,您问的是the os module's .walk() functionality。示例如下:

    import os
    for root, dirs, files in os.walk(".", topdown=False): # "." uses current folder
        # change it to a pathway if you want to process files not where your script is located
        for name in files:
            print(os.path.join(root, name))
    

    带有文件名输出,可以提供给您的 fixDat() 函数,例如:

    ./tmp/test.py
    ./amrood.tar.gz
    ./httpd.conf
    ./www.tar.gz
    ./mysql.tar.gz
    ./test.py
    

    请注意,这些都是字符串,因此您可以将脚本更改为:

    import os
    for root, dirs, files in os.walk(".", topdown=False):
        for name in files:
            if name.endswith('.dat'): # or some other extension
                print(os.path.join(root, name))
                fixDat(os.path.join(root, name))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-24
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多