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

时间:2016-12-08 16:32:24

标签: python

我是python的初学者。我有这个任务:

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

我已经编写了我的代码,它似乎工作,但它看起来很丑,不优雅。特别是3 if语句。我怎样才能缩短它?

这是我的代码:

function Cls(dep1, dep2) {
  this.dep1 = dep1;
  this.dep2 = dep2;
}

4 个答案:

答案 0 :(得分:0)

正则表达式可能正在运行,但如果您正在寻找一个共同的前缀,那么您可能会坚持使用str.startswith函数:

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

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

numbers = [int(filename.lstrip('spam').rstrip('.txt')) for filename in files]

要使用前导零填充小数字,您可以使用{: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)

答案 1 :(得分:0)

这对我有用:

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)

答案 2 :(得分:0)

这是我为此练习编写的脚本。 我希望它可以帮助任何人

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

答案 3 :(得分:0)

#?python3
#writing a program that takes folder path and a prefix of the folder name and identify gaps.
import os,shutil,re
def gaps(folder, prefix):
    folder = os.path.abspath(folder)
    os.chdir(folder)
    file_regex = re.compile(r'^%s00(\d).txt$'%prefix)
    number = 1
    for folder, subfolder, files in os.walk(folder):
        for file in files:
            oldname = os.path.basename(file)
            match_obj = file_regex.search(file)
            no = match_obj.group(1)
            no = int(no)
            if no == number:
                number +=1
            else:
                no = number
                newname = prefix + "00" + str(no) + '.txt'
                print(f'Changing {oldname} to {newname}')
                shutil.move(oldname,newname)
gaps("C:/Users/hp/Desktop/randomfolder",'spam')