如何在Python中使用shutil复制文件
我想把一个 .txt 文件从一个地方复制到另一个地方。这个代码在运行,但文件没有被复制。我哪里做错了呢?
import shutil
import os
src = "/c:/users/mick/temp"
src2 = "c:/users/mick"
dst = "/c:/users/mick/newfolder1/"
for files in src and src2:
if files.endswith(".txt"):
shutil.copy(files, dst)
4 个回答
0
import os, shutil
src1 = "c:/users/mick/temp/"
src2 = "c:/users/mick/"
dist = "c:/users/mick/newfolder"
if not os.path.isdir(dist) : os.mkdir(dist)
for src in [src1, src2] :
for f in os.listdir(src) :
if f.endswith(".txt") :
#print(src) # For testing purposes
shutil.copy(src, dist)
os.remove(src)
我觉得你出错的地方是,你试图把一个文件夹当成文件来复制,但你忘了要先处理文件夹里的文件。你只是简单地写了 shutil.copy("c:/users/mick/temp/", c:/users/mick/newfolder/")
。
1
我知道这个问题有点老了。不过这里有个简单的方法可以帮你完成你的任务。你可以根据需要更改文件的扩展名。要复制文件,你可以使用copy(),而要移动文件,你可以把它改成move()。希望这对你有帮助。
#To import the modules
import os
import shutil
#File path list atleast source & destination folders must be present not everything.
#*******************************WARNING**********************************************
#Make sure these folders names are already created while using the 'move() / copy()'*
#************************************************************************************
filePath1 = 'C:\\Users\\manimani\\Downloads' #Downloads folder
filePath2 = 'F:\\Projects\\Python\\Examples1' #Downloads folder
filePath3 = 'C:\\Users\\manimani\\python' #Python program files folder
filePath4 = 'F:\\Backup' #Backup folder
filePath5 = 'F:\\PDF_Downloads' #PDF files folder
filePath6 = 'C:\\Users\\manimani\\Videos' #Videos folder
filePath7 = 'F:\\WordFile_Downloads' #WordFiles folder
filePath8 = 'F:\\ExeFiles_Downloads' #ExeFiles folder
filePath9 = 'F:\\Image_Downloads' #JPEG_Files folder
#To change the directory from where the files to look // ***Source Directory***
os.chdir(filePath8)
#To get the list of files in the specific source directory
myFiles = os.listdir()
#To move all the '.docx' files to a different location // ***Destination Directory***
for filename in myFiles:
if filename.endswith('.docx'):
print('Moving the file : ' + filename)
shutil.move(filename, filePath4) #Destination directory name
print('All the files are moved as directed. Thanks')
1
shutils
是一个很方便的工具,可以用来复制文件,但如果你想要移动一个文件,可以使用下面的命令:
os.rename(oldpath, newpath)
2
你的for循环其实并没有在每个源文件中进行搜索。并且,你的for循环并不是在遍历每个源,而是在遍历src
和src2
中都存在的字母。这一点调整应该能解决你的问题。
import os
src = ["c:/users/mick/temp", "c:/users/mick"]
dst = "c:/users/mick/newfolder1/"
for source in src:
for src_file in os.listdir(source):
if src_file.endswith(".txt"):
old_path = os.path.join(source, src_file)
new_path = os.path.join(dst, src_file)
os.rename(old_path, new_path)
在这种情况下,你其实不需要用到shutil,因为它只是一个更强大的os.rename
,可以更好地处理不同的情况(根据我所知)。不过,如果“newfolder1”还不存在的话,你需要把os.rename()
换成os.renames()
,因为后者会尝试创建中间的目录。