'how to rename a file using python?
If the name is too long in the folder, there will be a problem, so I'm working on a code to change it at once. There's an error.
import os
import pathlib
p_dir = './data/'
for file in os.listdir(p_dir):
oldname = file
newname = file.split('_')[5] + '_SmmLogs.zip'
os.rename(oldname, newname)
I tried it like this, and from what I see, there seems to be no problem. but..
Traceback (most recent call last): File "d:/Coding/name/namechange.py", line 15, in os.rename(oldname, newname) FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。: 'PN8B744_M0001_NewMDCR_4x4mmP_AllatOnce_20220328000119153_SmmLogs.zip' -> '20220328000119153_SmmLogs.zip
There's an error like this. Is there any way...?
Solution 1:[1]
listdir returns a list of filenames. You need to add the path p_dir to your filenames
for file in os.listdir(p_dir):
file_name = file
oldname = str(file_name)
newname1 = file.split('_')[5] + '_SmmLogs.zip'
newname = str(newname1)
os.rename(os.path.join(p_dir,oldname), os.path.join(p_dir,newname))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PaNh |
