在Python中处理文件名

2024-10-17 08:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数,从原始数据文件中去掉两个空格:

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


Tags: 文件函数inimportreosaswith
1条回答
网友
1楼 · 发布于 2024-10-17 08:33:53

如果我理解正确,你是在问the ^{} module's ^{} 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))

相关问题 更多 >