0
我想創建一個簡單的函數,查找以某個字符串開頭的文件,然後將它們移動到一個新的目錄,但我不斷從shutil「IOError:[Errno 2 ]即使文件存在,也沒有這樣的文件或目錄:'18 -1.pdf'「。移動文件與shutil錯誤
import os
import shutil
def mv_files(current_dir,start):
# start of file name
start = str(start)
# new directory ro move files in to
new_dir = current_dir + "/chap_"+ start
for _file in os.listdir(current_dir):
# if directory does not exist, create it
if not os.path.exists(new_dir):
os.mkdir(new_dir)
# find files beginning with start and move them to new dir
if _file.startswith(start):
shutil.move(_file, new_dir)
我是否正確使用shutil?
正確的代碼:
import os
import shutil
def mv_files(current_dir,start):
# start of file name
start = str(start)
# new directory ro move files in to
new_dir = current_dir + "/chap_" + start
for _file in os.listdir(current_dir):
# if directory does not exist, create it
if not os.path.exists(new_dir):
os.mkdir(new_dir)
# find files beginning with start and move them to new dir
if _file.startswith(start):
shutil.move(current_dir+"/"+_file, new_dir)
謝謝,完全忽略了我只給文件名而不是完整路徑的事實。 –