我是新手,对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