问题
I am trying to create a simple function that finds files that begin with a certain string and then move them to a new directory but I keep getting the following kinds of errors from shutil "IOError: [Errno 2] No such file or directory: '18-1.pdf'", even though the file exists.
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)
Am I using shutil incorrectly?
correct code:
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)
回答1:
It looks like you aren't giving the full path to shutil.move
. Try:
if _file.startswith(start):
shutil.move(os.path.abspath(_file), new_dir)
If that fails, try printing _file
, and new_dir
along with the result of os.getcwd()
and adding them to your answer.
来源:https://stackoverflow.com/questions/22230043/error-moving-file-with-shutil