當前位置:首頁 » 文件管理 » python文件夾復制文件

python文件夾復制文件

發布時間: 2023-04-18 07:45:43

A. python 中如何實現對文件的復制、粘貼

file類中沒有提供專門的文件復制函數,因此只能通過使用文件的讀寫函數來實現文件的復制。這里僅僅給出範例:
src = file("myfile.txt", "w+")
temp = ["hello world! \n"]
src.writelines(temp)
src.close()

src = file("myfile.txt", "r+")
des = file("myfile2.txt", "w+")
des.writelines(src.read())
src.close()
des.close()

shutil模塊是另一個文件,目錄的管理介面,提供了一些用於復制文件,目錄的函數。file()函數可以實現文件的拷貝,聲明如下:
file(src, des)
文件的剪切可以使用move()函數模擬,聲明如下:
move(src,des)
功能:移動一個文件或者目錄到指定的位置,並且可以根據參數des重命名移動後的文件。

B. Python的shutil模塊中文件的復制操作

shutil.file(src, dst):將名為src的文件的內容復制到名為dst的文件中 。

src, dst是文件名

shutil.(source, destination)
shutil.() 函數實現文件復制功能,將 source 文件復制到 destination 文件夾中,兩個參數都是字元串格式。如果 destination 是一個文件名稱,那麼它會被用來當作復制後的文件名稱,即等於 復制 + 重命名。

source一定是文件名,destination可以是文件名也可以是文件夾名

舉例如下:

shutil 模塊

C. 用python如何將文件夾內部分指定文件名的文件復制到目標文件夾,大佬求教!

import glob
import shutil

def _file(names,old_name,new_name):
for name in names:
filename = name.split("\\")[-1]
#filename:從路徑中截取文件名
shutil.file(old_name + filename, new_name + filename)

files = glob.glob(r'D:/A/1*.txt')
#files : 搜索得到的符合條件(帶有1開頭的txt)的文件列表
old_path = r'D:/A/'
new_path = r'D:/B/'
_file(files,old_path,new_path)

D. python 怎麼將輸入目錄內的文件拷貝至另一個目錄的同名文件夾

這是最近寫的一個類似代碼,你拿去改改
import shutil
import os
import logging
import sys

logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

def cp_or_mv2(src_file, des_dir, is_):
print(src_file, des_dir)
if os.path.isfile(src_file):
logger.info(f'from file {src_file}')
if is_:
shutil.2(src_file, des_dir)
logger.info(f' to {des_dir}')
else:
des_file = os.path.join(des_dir, src_file)
shutil.move(src_file, des_file)
logger.info(f'move to {des_file}')
else:
logger.info(f'from dir {src_file}')
des_dir_level1 = os.path.join(des_dir, src_file)
shutil.tree(src_file, des_dir_level1, dirs_exist_ok=True)
logger.info(f'to {des_dir_level1}')
if not is_:
shutil.rmtree(src_file)
logger.info(f'deleted {src_file}')

def process_files_in_txt(txt_file, src_dir, des_dir, is_=True):
os.chdir(src_dir)
with open(txt_file, 'r', encoding='utf8', errors='ignore') as f:
for line in f.readlines():
src_file = line.strip()
# logger.info(src_file)
if os.path.exists(src_file):
cp_or_mv2(src_file, des_dir, is_)
else:
logger.warning(f'{src_file} missing!')

if __name__ == '__main__':
process_files_in_txt(r"D:\D\需要拷貝.txt", # 哪些文件(夾)
r"D:\D\Desktop", # 從哪個文件夾
r"D:\D\新建文件夾", # 到哪個文件夾
is_=False) # True復制,False剪切

E. python把一個文件夾下的所有東西復制到另一個文件夾下

fromshutilimport
importos
importre
dest_dir=raw_input('Pleaseenterdestinationpath:(splitpathwith"/")')
source_dir=raw_input('Pleaseentersourcepath:(splitpathwith"/")')

ifnotdest_dir.endswith('/'):
dest_dir+='/'
ifnotsource_dir.endswith('/'):
source_dir+='/'
ifos.path.isdir(dest_dir)andos.path.isdir(source_dir):
forroot,dirs,filesinos.walk(source_dir):
foriinxrange(0,files.__len__()):
sf=os.path.join(root,files[i])
dst=re.sub('([A-Za-z]:/.*?)/',dest_dir,root)
ifnotos.path.exists(dst):
os.makedirs(dst)
(sf,dst)
print'Done!'

else:
raiseException('Wrongpathentered!')

raw_input()

F. python 復制文件

報錯多半是這句targetDir = targetDir+'/'+os.path.split(sourceDir)[1]

你這句把本來的targetDir覆蓋了,導致後面的文件的目標文件夾被修改


發個我寫的吧,參考下吧

defFile(sourceDir,targetDir):
ifnotos.path.exists(targetDir):
os.makedirs(targetDir)

forfilenameinos.listdir(sourceDir):
path=os.path.join(sourceDir,filename)
ifos.path.isdir(path):
targetSubDir=os.path.join(targetDir,filename)
File(path,targetSubDir)
else:
targetPath=os.path.join(targetDir,filename)
open(targetPath,'wb').write(open(path,'rb').read())

G. Python復制文件命令合集

python的shutil模塊提供了便捷的復制文件命令

shutil.(srcfile,dstfile)  #拷貝文件,目標文件必須存在,否則就會報錯

shutil.file(srcfile,dstfile)  #拷貝文件,目標 文件無需巧蘆凳存在

shutil.tree(srcdir,dstdir)    #srcdir為源目錄,dstdir為目標目錄,復制時,如果dstdir已經存在時,會報FileExistsError錯誤,提示「當文件已存在時,無法創建該文件」

shutil.mode(src, dst)     # 僅拷貝許可權。內孝旅容、組、用戶均不變,目標文件嘩昌必須存在

H. 用python把文件夾下的所有文件包括文件夾裡面的文件都拷貝到同一個目錄下

defchange(path,path1):
forfinos.listdir(path):
ifos.path.isfile(path+os.path.sep+f):
a,b=os.path.splitext(f)
ifb!='.py':
shutil.(path+os.sep+f,path1)
elifos.path.isdir(path+os.path.sep+f):
change(path+os.sep+f,path1)
if__name__=='__main__':
path='D:\workspace\python'
path1='D:\workspace\python\filepath'
change(path,path1)

你好,我把change稍微改了一下,看看行不

I. 如何用python復制文件和文件夾

這個方法不能把文件夾復制到文件夾裡面去。

10.shutil.tree('E:\test\good', 'E:\test\vivi')

tree不能把文件夾復制到已存在的文件夾裡面去。

11.shutil.tree('E:\test\good', 'E:\test\new folder')

只能復制到新創建的文件夾裡面。

有相同名字的文件,就會出錯,注意修改文件名。

J. python 怎麼把文件夾下所有文件復制

import
os
import
os.path
rootdir
=
「d:\data」
#
指明被遍歷的文件夾
for
parent,dirnames,filenames
in
os.walk(rootdir):
#三個參數:分別返回1.父目錄
2.所有文件夾名字(不含路徑)
3.所有文件名字
for
dirname
in
dirnames:
#輸出文件夾信息
print
"parent
is:"
+
parent
print
"dirname
is:"
+
dirname
for
filename
in
filenames:
#輸出文件信息
print
"parent
is:"
+
parent
print
"filename
is:"
+
filename
print
"the
full
name
of
the
file
is:"
+
os.path.join(parent,filename)
#輸出文件路徑信息

熱點內容
subplotpython 發布:2025-05-14 06:53:51 瀏覽:661
豎屏大屏導航工廠密碼一般是多少 發布:2025-05-14 06:49:29 瀏覽:806
如何在手機里設置無線網密碼 發布:2025-05-14 06:47:54 瀏覽:120
動態ip文件伺服器 發布:2025-05-14 06:44:22 瀏覽:891
文字分行的腳本有什麼 發布:2025-05-14 06:33:10 瀏覽:288
svn小烏龜怎麼配置 發布:2025-05-14 06:31:43 瀏覽:393
視頻播放器android 發布:2025-05-14 06:31:43 瀏覽:720
android工作室 發布:2025-05-14 06:26:00 瀏覽:658
汽車官方配置表如何下載 發布:2025-05-14 06:21:41 瀏覽:800
停車項目源碼 發布:2025-05-14 06:20:05 瀏覽:358