I am new to python and programming generally
I have 1200 text files in a folder, in the following format:
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
I want to rename the files below 1000 to add leading 0's so they all have the same number of digits, for instance, 0001, 0050, 0300
This is my code so far, but am stuck:
#!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)
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
Whenever a number has leading zeros it seams to either cause a syntax error (if an 8 or 9 is in the number), or results in max calculating the wrong value.
Use the zfill() String Method to Pad a String With Zeros in Python. The zfill() method in Python takes a number specifying the desired length of the string as a parameter and adds zeros to the left of the string until it is of the desired length.
As you were said in comments, str.zfill
is one possible and simple solution.
You have just to change your getfiles
function:
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
Modify your append method like this (mentioned by @gtlambert and @zondo):
# Was trying to append just one 0 to numbers <10
file_number.zfill(4)
Python string zfill
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With