我正在尝试创建一个简单的函数,查找以某个字符串开头的文件,然后将它们移动到新目录,但我不断从shutil“IOError:[Errno 2]没有这样的文件或目录:' 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)
您似乎没有提供完整路径shutil.move
. Try:
if _file.startswith(start):
shutil.move(os.path.abspath(_file), new_dir)
如果失败,请尝试打印_file
, and new_dir
以及结果os.getcwd()
并将它们添加到您的答案中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)