gpt4 book ai didi

Python - 将前导 0 添加到文件编号

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:23 25 4
gpt4 key购买 nike

我是 python 和编程的新手我在一个文件夹中有 1200 个文本文件,格式如下:
James - 1 - 如何....txt
莎拉 - 2 - 如何....txt
Steph - 3 - 如何....txt
...
玛丽亚 - 200 - 如何....txt
...
拉什福德 - 1200 - 如何.......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 是一种可能且简单的解决方案。

您只需更改您的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

关于Python - 将前导 0 添加到文件编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35726163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com