关闭文件时出错 [英] error moving file with shutil
问题描述
我正在尝试创建一个简单的函数,该函数查找以某个字符串开头的文件,然后将其移动到新目录,但是我不断从shutil中收到以下类型的错误: IOError:[Errno 2]没有此类文件或目录:'18 -1.pdf',即使文件存在。
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)
我不正确地使用shutil吗?
Am I using shutil incorrectly?
正确的代码:
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)
推荐答案
好像你不是提供 shutil.move
的完整路径。尝试:
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)
如果失败,请尝试打印 _file
和 new_dir
以及 os.getcwd()
的结果,并将它们添加到您的答案中。
If that fails, try printing _file
, and new_dir
along with the result of os.getcwd()
and adding them to your answer.
这篇关于关闭文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!