I am trying to rename files from a directory. But for some reason which I do not know, the files are not getting renamed.
Code:
def extract_info_from_filename(file_name):
parts = file_name.split('Z')
part1 = parts[0]
part2 = parts[1]
return part1, part2
def find_csv_files_to_rename(directory):
for root, dirs, files in os.walk(directory):
if 'rename' in root:
for file_name in files:
if file_name.endswith('.csv'):
original_file_path = root + '/' + file_name
print(f"File Name: {file_name}, Extracted Info: {extract_info_from_filename(file_name)}")
extracted_parts = extract_info_from_filename(file_name)
new_file_name = f"{extracted_parts[0]}Z_treatment{extracted_parts[1]}"
print(f"New File name: {new_file_name}")
#new_file_path = os.path.join(root,new_file_name)
new_file_path =root+'/'+new_file_name
print(f"New File Path Exists: {os.path.exists(new_file_path)}")
print(f"Original File Path Exists: {os.path.exists(original_file_path)}")
print(f"Root: {root}")
print(f"New file path: {new_file_path}")
if not os.path.exists(new_file_path):
os.rename(original_file_path, new_file_path)
if os.rename(original_file_path, new_file_path):
print(f'Renamed: {file_name} -> {new_file_name} \n')
else:
print(f'File already exists: {original_file_path} \n')
root_directory = 'input_files'
find_csv_files_to_rename(root_directory)
Output is:
File Name: 2023-07-08T00_28_04_750Z_Aachen_01.01.2022-P06.2023.csv, Extracted Info: ('2023-07-08T00_28_04_750', '_Aachen_01.01.2022-P06.2023.csv')
New File name: 2023-07-08T00_28_04_750Z_treatment_Aachen_01.01.2022-P06.2023.csv
New File Path Exists: False
Original File Path Exists: False
Root: input_files\rename_and_validate\XXXX\year=2023\month=07\day=08\XXXX
New file path: input_files\rename_and_validate\XXXX\year=2023\month=07\day=08\XXXX/2023-07-08T00_28_04_750Z_treatment_Aachen_01.01.2022-P06.2023.csv
Error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'input_files\\rename_and_validate\\XXXX\\year=2023\\month=07\\day=08\\XXXX/2023-07-08T00_28_04_750Z_Aachen_01.01.2022-P06.2023.csv' -> 'input_files\\rename_and_validate\\XXXX\\year=2023\\month=07\\day=08\\XXXX/2023-07-08T00_28_04_750Z_treatment_Aachen_01.01.2022-P06.2023.csv'
I kindly want to know the solution. I have tried all possible way of addressing the issue, from the modifying the paths (using .join function). But seems like the same issue.
Answer was incorrect. Author found another solution The issue is resolved: It was about enabling LongPath in my windows through regedit