编写一个python程序来查找具有给定前缀的所有文件并填补空白

2024-09-27 19:27:37 发布

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

我是python的初学者。我的任务是:

编写一个程序,在一个文件夹中查找具有给定前缀的所有文件,如spam001.txt、spam002.txt等等,并查找编号中的任何空白(例如,如果有spam001.txt和spam003.txt,但没有spam002.txt)。让程序重命名所有后面的文件来缩小这个差距。在

我已经写了我的代码,它似乎可以工作,但它看起来丑陋,不优雅。尤其是3if语句。我怎样才能缩短它?在

这是我的代码:

# My main idea is to copy the file which is not in right order,
# and rename it, then delete it.

import os, re, shutil


# Arguments: folder, prefix
def fillGap(folder,prefix):


    # Create regex with prefix + number + extension.
    fileRegex = re.compile(r'(%s)((\d)(\d)(\d))\.txt' % prefix)

    # Makee sure the path is absolute.
    folder = os.path.abspath(folder)

    # When I commented the following one line, the program outptu is
    # FileNotFoundError: [Errno 2] No such file or directory:   'spam004.txt'
    os.chdir(folder)  # This line is to avoid the FileNotFoundError.

    # Make a list to contain the file with prefix.
    fileNames = list()
    for filename in os.listdir(folder):
        if re.search(fileRegex, filename):
            fileNames.append(filename)
    # Make sure the fileName in the list have a right order.

    fileNames.sort()
    print(fileNames)
    # Find the gap through incremting loops
    for i in range(len(fileNames)):
        mo = re.search(fileRegex, fileNames[i])
        if int(mo.group(2)) == i + 1:
            continue
        # The group(2) has three digits, so it need to 3 Ifs.
        # Copy the old file and rename it then delete the old one.
        if i + 1 < 10:
            shutil.copy
            newFileName =prefix + '00' + str(i + 1) + '.txt'
            shutil.copy(fileNames[i], newFileName)
            os.unlink(fileNames[i])
        elif i + 1 < 100:
            shutil.copy(fileNames[i], prefix + '0' + str(i+1) + '.txt')
            os.unlink(fileNames[i])
        else:
            shutil.copy(fileNames[i], prefix + str(i+1) + '.txt')
            os.unlink(fileNames[i])

folder = '/home/jianjun/spam/'
prefix = 'spam'

fillGap(folder, prefix)

Tags: thetoinretxtprefixisos
3条回答

regex可能正在工作,但是如果您正在寻找一个公共前缀,那么您可以使用str.startswith函数:

files = [filename for filename in os.listdir(folder) if filename.startswith('spam')]

然后要找到数字,你可以去掉前缀和文件扩展名(不确定这一步是否必要,为什么需要旧的数字?)公司名称:

^{pr2}$

要用前导零填充小数字,您可以使用{:0>3}.format,例如,请参见:

>>> '{:0>3}'.format(2)
002

因此,与其使用prefix + str(i+1) + '.txt'和变体,不如将其简化为:

newfilenames = ['spam{:0>3}.txt'.format(number+1) for number in range(len(files))]

假设您在创建数字之前sort您的文件现在有一个旧名称和新名称的列表,您可以通过迭代来重命名它们:

for oldname, newname in zip(files, newfilenames):
    shutil.copy(oldname, newname)
    os.unlink(oldname)

这是我为这个练习写的脚本。 我希望这对任何人都有帮助

import os, re

directory = "c:\\users\\pt world\\documents"

os.chdir(directory)

regexObject = re.compile(r"^spam00(\d).txt$")

number = 1


for folder, subfolder, filename in os.walk(directory):
    for filenames in filename:
         matchObject = regexObject.search(filenames)
         if matchObject:
            if int(matchObject.group(1)) == number:
                number += 1

         else: 
            os.rename(matchObject.group(),\
            "spam00{}.txt".format(number))
                   number += 1

这对我很有效:

def gaps(dire, prefix):

    import os, re, shutil

    folder =  os.path.abspath(dire)
    sablon = re.compile(r'''(%s)(\d\d\d).txt''' % prefix)
    matchlist = []

    for filename in os.listdir(folder):
        match = sablon.match(filename)
        if match:
            matchlist.append(filename)
            if int(match.group(2)) == len(matchlist):
                continue
            else:
                print(filename + ' is the ' + str(len(matchlist)) + 'th file')
                if len(matchlist) < 9:
                    print(filename + ' will be renamed: ' + prefix + '00' + str(len(matchlist)) + '.txt')
                    newname = prefix + '00' + str(len(matchlist)) + '.txt'
                    oldname = os.path.join(folder, filename)
                    newname = os.path.join(folder, newname)
                    shutil.move(oldname, newname)

                elif 10 <= len(matchlist) < 100:
                    print(filename + ' will be renamed: ' + prefix + '0' + str(len(matchlist)) + '.txt')
                    newname = prefix + '0' + str(len(matchlist)) + '.txt'
                    oldname = os.path.join(folder, filename)
                    newname = os.path.join(folder, newname)
                    shutil.move(oldname, newname)

相关问题 更多 >

    热门问题