我试图用Python将文件从文件夹移动到桌面。但我得到错误。 以下是我的代码和错误:
import shutil
import os
source_dir = 'C:\Users\dupakunt\Desktop\Testdir'
os.makedirs(source_dir)
os.chdir(source_dir)
open("newfile1.txt", "w")
open("newfile2.txt", "w")
target = 'C:\Users\dupakunt\Desktop'
dir_list = os.listdir(source_dir)
for x in source_dir:
print x
shutil.move(x,target)
错误:
Traceback (most recent call last):
File "cleanup-undo.py", line 12, in <module>
shutil.move(x,target)
File "C:\Python27\lib\shutil.py", line 302, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'C'.
答案 0 :(得分:0)
source_dir
是目录名称,您希望运行目录中的dir_list
个文件。还有一些其他项目可以参加
/
分隔符。chdir
和绝对路径令人困惑。我建议尽可能避免chdir
,只需使用os.path.join
使相对路径成为绝对路径。with
条款。您的代码适用于cpython,但是对于其他一些变体,open
完成后文件仍可能会打开。实施例
import shutil
import os
source_dir = r'C:\Users\dupakunt\Desktop\Testdir'
os.makedirs(source_dir)
with open(os.path.join(source_dir, "newfile1.txt"), "w"):
pass
with open(os.path.join(source_dir, "newfile2.txt"), "w"):
pass
target = r'C:\Users\dupakunt\Desktop'
dir_list = os.listdir(source_dir)
for x in dir_list:
if os.path.isfile(x):
x = os.path.join(target, x)
print x
shutil.move(x,target)