简体   繁体   中英

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...?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM