Python - 在文件编号前添加前导0

5

我是新手,对Python和编程不太熟悉。

我有一个文件夹内有1200个文本文件,格式如下:

James - 1 - How to... .txt

Sarah - 2 - How to... .txt

Steph - 3 - How to... .txt

...

Mariah - 200 - How to... .txt

...

Rashford - 1200 - How to... .txt

我想将文件名低于1000的文件名前添加0,使它们都有相同的位数,例如0001、0050、0300等。

这是我目前的代码,但我卡住了:

#!python3

import os
from tkinter import filedialog

cleaned_files = []

root_folder = filedialog.askdirectory()
os.chdir(root_folder)
folder_files = os.listdir(root_folder)

# Filter out files starting with '.' and '_'
cleaned_files = []
for item in folder_files:
    if item[0] == '.' or item[0] == '_':
        pass
    else:
        cleaned_files.append(item)


# Find file names of the root folder and save them


def getFiles(files):
    for file in files:
        file_start, file_number, file_end = file.split('-')
        file_number.strip()

        # Was trying to append just one 0 to numbers <10
        if int(file_number) < 10:
            print(file_number)
        else:
            pass
getFiles(cleaned_files)

你想要使用str.zfill()函数 - 这会在需要的地方给你的字符串添加前导零。 - gtlambert
@gtlambert,您能否给我展示一个在添加零后重命名的示例? - alfiepoleon
2
你真的需要将你的问题缩小到具体的某个方面 - 然后我才能提供详细的帮助! - gtlambert
2个回答

5

正如评论中所说,str.zfill是一种可能且简单的解决方案。

您只需更改getfiles函数:

def getFiles(files):
    for file in files:
        file_start, file_number, file_end = file.split('-')
        num = file_number.split().zfill(4)  # num is 4 characters long with leading 0

        new_file = "{}- {} -{}".format(file_start, num, file_end)
        # rename or store the new file name for later rename

4
将您的append方法修改为以下内容(由@gtlambert和@zondo提出):
    # Was trying to append just one 0 to numbers <10
    file_number.zfill(4)

Python string zfill


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接