[英]FileNotFoundError when trying to rename all the files in a directory
我正在編寫一個 python 腳本來重命名給定文件夾中的所有文件。 python 腳本與images/jaguar
文件一起存在於我的jl-classifier
。 我正在嘗試運行以下腳本以獲取文件夾中的每個文件並將其重命名為這種格式:
jaguar_[#].jpg
但它拋出以下錯誤:
Traceback (most recent call last):
File "/home/onur/jaguar-leopard-classifier/file.py", line 14, in <module>
main()
File "/home/onur/jaguar-leopard-classifier/file.py", line 9, in main
os.rename(filename, "Jaguar_" + str(x) + file_ext)
FileNotFoundError: [Errno 2] No such file or directory: '406.Black+Leopard+Best+Shot.jpg' -> 'Jaguar_0.jpg'
這是我的代碼:
import os
def main():
x = 0
file_ext = ".jpg"
for filename in os.listdir("images/jaguar"):
os.rename(filename, "Jaguar_" + str(x) + file_ext)
x += 1
if __name__ == '__main__':
main()
os.listdir
只返回文件名(不是文件路徑...)
嘗試以下
for filename in os.listdir("images/jaguar"):
filepath = os.path.join("images/jaguar",filename)
new_filepath = os.path.join("images/jaguar","Jaguar_{0}{1}".format(x,file_ext))
os.rename(filepath, new_filepath)
直言不諱幾乎總是通往更幸福生活的道路
為了使用os.rename()
,您需要提供絕對路徑。
我建議將第 9 行替換為os.rename(os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/{filename}"), os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/Jaguar_{str(x)}{file_ext}")
os.path.expanduser()
允許您使用“~”語法來幫助 abs 文件路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.