![](/img/trans.png)
[英]FileNotFoundError when using os.rename() in Python
[英]os.rename does not succeed in renaming in subdirectories, throws FileNotFoundError despite using glob.glob with recursive=True
以下代碼旨在將 cwd 和子目錄中名為“notes”的文件重命名為“notes.html.pmd”。 那些仍然在 Python3.7 和更早版本上的人需要擺脫海象運算符並替換
fileListOld = glob.glob(f"{(cwd := os.getcwd())}/**/{old_name}", recursive=True)
和
cwd = os.getcwd()
fileListOld = glob.glob(f"{cwd}/**/{old_name}", recursive=True)
為了運行這段代碼。 無論如何,代碼如下:
#!/usr/bin/env python3.8
import glob, os
old_name = r"notes"
new_name = r"notes.html.pmd"
fileListOld = glob.glob(f"{(cwd := os.getcwd())}/**/{old_name}", recursive=True)
print(fileListOld)
for f in fileListOld:
os.rename(old_name, new_name)
問題是僅在 CWD 中而不是在子目錄中重命名“notes”。 此外 Python 拋出以下錯誤:
Traceback (most recent call last):
File "./rename.py", line 17, in <module>
os.rename(old_name, new_name)
FileNotFoundError: [Errno 2] No such file or directory: 'notes' -> 'notes.html.pmd'
我知道我的問題和他們的有些相似。 然而,不同之處在於我的代碼還打算重命名子目錄中的文件,因此recursive=True parameter 。
我究竟做錯了什么? 遞歸重命名文件的最簡單方法是什么?
您一遍又一遍地將相同的old_name == "notes"
重命名為new_name == "notes.html.pmd"
而不是使用glob.glob
提供的路徑。 我會使用pathlib :
#!/usr/bin/env/python3
from pathlib import Path
old_name = "notes"
new_name = "notes.html.pmd"
for old_path in Path(".").glob(f"**/{old_name}"):
old_path.rename(old_path.parent / new_name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.