[英]How do i copy files with shutil in python
我試圖將.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)
您的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)
對於這種情況,您不需要關閉,因為它只是功能更強大的os.rename
,它嘗試更好地處理不同的場景(據我所知)。 然而,如果“newfolder1”是不是已經existant比你將要替換os.rename()
與os.renames()
作為這個嘗試創建其間的目錄。
shutils
對於復制很有用,但可以移動文件
os.rename(oldpath, newpath)
我知道這個問題有點老了。 但是,這是完成任務的簡單方法。 您可以根據需要更改文件擴展名。 對於復制,您可以使用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')
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/")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.