使用shutil移动文件时出错
我正在尝试创建一个简单的函数,用来找到以某个特定字符串开头的文件,然后把它们移动到一个新的文件夹里。但是我总是收到这样的错误信息:shutil 的 "IOError: [Errno 2] No such file or directory: '18-1.pdf'",尽管这个文件是存在的。
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)
1 个回答
5
看起来你没有给出shutil.move
的完整路径。试试这个:
if _file.startswith(start):
shutil.move(os.path.abspath(_file), new_dir)
如果这样还是不行,试着打印一下_file
和new_dir
,还有os.getcwd()
的结果,然后把这些信息加到你的回答里。