使用shutil移动文件在python中无法正常工作



试图将文件从一个文件夹移动到另一个文件夹,但始终出现如下错误。我在sample1源中确实有这个Model.xlsx文件,但我无法移动它。我试图使用"shutil.move(os.path.abspath(f(,dest1("绝对路径,但这给了我不同的错误。它实际上是随机挑选一个文件夹。谢谢

import shutil
import os

source = 'D:/Desktop/sample1'
dest1 = 'D:/Downloads/sample2'
dest2 = 'D:/Downloads/sample3'

files = os.listdir(source)
for f in files:
if (f.startswith("Model.xlsx")):
shutil.move(f, dest1)
elif (f.startswith("Intel") or f.startswith("intel")):
shutil.move(os.path.abspath(f), dest2)

错误:

Traceback (most recent call last):
File "D:UsersKSanala1AppDataLocalProgramsPythonPython37libshutil.py", line 566, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Model.xlsx' -> 'D:/Downloads/sample2\Model.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Users/KSanala1/PycharmProjects/pythonProject/main.py", line 16, in <module>
shutil.move(f, dest1)
File "D:XXXAppDataLocalProgramsPythonPython37libshutil.py", line 580, in move
copy_function(src, real_dst)
File "D:XXXAppDataLocalProgramsPythonPython37libshutil.py", line 266, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "D:XXXAppDataLocalProgramsPythonPython37libshutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'Model.xlsx'
Process finished with exit code 1

您需要给出shutil.move的完整路径,在您的情况下:os.path.join(源,f(

files = os.listdir(source)
for f in files:
f_path = os.path.join(source,f)
if (f.startswith("Model.xlsx")):
shutil.move(f_path , dest1)
elif (f.startswith("Intel") or f.startswith("intel")):
shutil.move(os.path.abspath(f_path), dest2)

os.listdir仅返回文件名列表。要获得实际路径(您需要(,您需要将原始文件路径(即os.listdir的参数(与文件名连接起来

files = os.listdir(source)
for f in files:
fpath = os.path.join(source, f)

现在您有了一个合理的路径,而不仅仅是一个文件名。

然而,将像source = 'D:/Desktop/sample1'这样的硬编码路径与os.path函数混合不是一个好主意。首先考虑使用os.path构建路径

source = os.path.join('D:', os.sep, 'Desktop', 'sample1')

最新更新