当前位置:首页 » 文件管理 » 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)
#输出文件路径信息

热点内容
柱子箍筋加密区长度 发布:2025-05-14 10:18:29 浏览:351
云服务器和内网穿透哪个好 发布:2025-05-14 10:16:41 浏览:627
安徽新能源网络配置是什么 发布:2025-05-14 10:06:24 浏览:631
pinode搭建服务器 发布:2025-05-14 10:04:23 浏览:4
电脑服务器ip名称 发布:2025-05-14 10:01:09 浏览:749
connectorpython 发布:2025-05-14 09:48:50 浏览:763
配置不好怎么办 发布:2025-05-14 09:46:40 浏览:623
数据流程图中的数据存储是指 发布:2025-05-14 09:46:39 浏览:446
我的世界服务器id前缀mod 发布:2025-05-14 09:45:53 浏览:831
完整后台网站源码 发布:2025-05-14 09:45:46 浏览:456