當前位置:首頁 » 編程語言 » python目錄復制

python目錄復制

發布時間: 2022-04-12 03:55:28

python 怎麼復制文件夾下部分文件

1、可以配置無密碼訪問或者用sshpass在shell中存密碼
2、實例
ip.txt包含ip列表,每行一個ip
test.sh保護修改配置的命令或者直接修改好,復制到遠程指定路徑。
3、代碼
#!/bin/sh
for
ip
in
`cat
ip.txt`;
do
echo
${ip};
scp
-
P22

test.sh
root...

Ⅱ python中怎樣將文件拷貝到指定的目錄下

代碼:

import os
import shutil
from shutil import Error
from shutil import stat
from shutil import 2
src = "" #需要復制的文件目錄
dst = "" #目標目錄
def jiecptree(src, dst, symlinks=False, ignore=None): #聲明函數 ree( 要復制的目錄,目標目錄,復制符號連接內容到新目錄,沒有要忽略文件)
names = os.listdir(src) #獲得要復制目錄的文件名列表,賦給變數 names
if ignore is not None: #如果 ignore 不是None值
ignored_names = ignore(src, names) # src目錄中要忽略文件的名字賦給 ignored_names
else: # 否則
ignored_names = set() #ignore_name 被 不重復空元素集 賦值
if os.path.isdir(dst):
pass
else:
os.makedirs(dst)
# print"dstfirst:"+dst
errors = [] #聲明 errors列
for name in names: #將names里的元素循環復制給name
if name in ignored_names: #如果name在要求被忽略的列里出現
continue #繼續for循環(跳回for,從新循環下個元素)
srcname = os.path.join(src, name) #將路徑名(src)添加到文名(name)之前然後賦值給 srcname
dstname = os.path.join(dst, name) #將路徑名(dst)添加到文名(name)之前然後賦值給 dstcname
from shutil import Error
# print "name:"+name
# print "src:"+src
# print "dst:"+dst
try: #嘗試
if os.path.islink(srcname):
continue
elif os.path.isdir(srcname): #如果srcname路徑是存在
jiecptree(srcname, dstname, symlinks, ignore)
elif os.path.isdir(dstname):
os.remove(dstname)
2(srcname, dstname)
else: # 否則
2(srcname, dstname) # 復制srcname到dstname
# print "srcname:"+srcname
# print "dstname:"+dstname
# XXX What about devices, sockets etc.? #怎樣裝置
except (IOError, os.error), why: #除(IOError[與文件有關的異常],操作系統異常)外,返回原因
errors.append((srcname, dstname, str(why))) # 向errors列里添加,(要復制的目錄,目標目錄,錯誤原因)
# catch the Error from the recursive jiecptree so that we can 從遞歸復制中捕捉這個錯誤,以便於我們能繼續復制其他文件
# continue with other files
except Error, err: #除錯誤外,返回錯誤:
errors.extend(err.args[0]) #擴展 errors 列,添加(err.args[0] 元素)
try: #嘗試
stat(src, dst) # 從src復制許可權位,上次訪問時間,最後修改時間 到 dst,
except WindowsError: # 除 Windows錯誤 外:
# can't file access times on Windows 在Windows上無法復制文件訪問時間
pass # 通過(不作任何處理)
except OSError, why: # 除 操作系統錯誤 外,返回原因:
errors.extend((src, dst, str(why))) #擴展 errors 列,添加(要復制的目錄,目標目錄,錯誤原因)
if errors: # 如果錯誤
raise Error(errors) # 提示錯誤

更多相關內容可參考資料http://www.viiboo.cn

Ⅲ 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()

Ⅳ python 實現一級目錄下的所有文件與文件夾到指定目錄

'''
python3 實現
將a目錄下所有文件和文件夾到b目錄
'''
import os, shutil

#src 原始目錄, des 目標目錄
def sourcecpy(src, des):
src = os.path.normpath(src)
des = os.path.normpath(des)
if not os.path.exists(src) or not os.path.exists(src):
print("文件路徑不存在")
sys.exit(1)
#獲得原始目錄中所有的文件,並拼接每個文件的絕對路徑
os.chdir(src)
src_file = [os.path.join(src, file) for file in os.listdir()]
for source in src_file:
#若是文件
if os.path.isfile(source):
shutil.(source, des) #第一個參數是文件,第二個參數目錄
#若是目錄
if os.path.isdir(source):
p, src_name = os.path.split(source)
des = os.path.join(des, src_name)
shutil.tree(source, des) #第一個參數是目錄,第二個參數也是目錄

Ⅳ 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)
#輸出文件路徑信息

Ⅵ 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())

Ⅶ 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重命名移動後的文件。

Ⅷ 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剪切

Ⅸ python復制文件到目錄

你後面說的不能。。而是 。。 沒看明白

Ⅹ Python如何將指定文件夾(包括裡面的內容)到指定目錄(已存在)

使用這個方法

importshutil,errno

defanything(src,dst):
try:
shutil.tree(src,dst)
exceptOSErrorasexc:#python>2.5
ifexc.errno==errno.ENOTDIR:
shutil.(src,dst)
else:raise
熱點內容
登陸認證失敗請檢查伺服器地址 發布:2025-05-20 07:06:55 瀏覽:831
無限分類實現php 發布:2025-05-20 06:57:40 瀏覽:681
數據結構c語言版嚴蔚敏李冬梅 發布:2025-05-20 06:55:05 瀏覽:449
iphone快捷訪問 發布:2025-05-20 06:55:05 瀏覽:929
如何加密硬碟分區 發布:2025-05-20 06:52:29 瀏覽:363
反編譯gd 發布:2025-05-20 06:52:23 瀏覽:838
java源碼知乎 發布:2025-05-20 06:47:59 瀏覽:483
dos解壓縮命令 發布:2025-05-20 06:47:57 瀏覽:639
安卓傳數據給蘋果的軟體叫什麼 發布:2025-05-20 06:42:48 瀏覽:804
怎麼樣盤解壓力 發布:2025-05-20 06:37:08 瀏覽:85