python經(jīng)典實例—復制文件
提問人:楊紫紅發(fā)布時間:2020-11-26
import shutil
import os
import os.path
src = " d:\\download\\test\\myfile1.txt "
dst = " d:\\download\\test\\myfile2.txt "
dst2 = " d:/download/test/測試文件夾.txt "
dir1 = os.path.dirname(src)
print ( " dir1 %s " % dir1)
if (os.path.exists(src) == False):
os.makedirs(dir1)
f1 = open(src, " w " )
f1.write( " line a\n " )
f1.write( " line b\n " )
f1.close()
shutil.copyfile(src, dst)
shutil.copyfile(src, dst2)
f2 = open(dst, " r " )
for line in f2:
print (line)
f2.close()
# 測試復制文件夾樹
try :
srcDir = " d:/download/test "
dstDir = " d:/download/test2 "
# 如果dstDir已經(jīng)存在,那么shutil.copytree方法會報錯!
# 這也意味著你不能直接用d:作為目標路徑.
shutil.copytree(srcDir, dstDir)
except Exception as err:
print (err)
'''
知識點:
* shutil.copyfile:如何復制文件
* os.path.exists:如何判斷文件夾是否存在
* shutil.copytree:如何復制目錄樹
'''
總結(jié):4個函數(shù)
·os.path.dirname(path)
·os.path.exists(path)
·shutil.copyfile(src, dst)
·shutil.copytree(srcDir, dstDir)
import os
import os.path
src = " d:\\download\\test\\myfile1.txt "
dst = " d:\\download\\test\\myfile2.txt "
dst2 = " d:/download/test/測試文件夾.txt "
dir1 = os.path.dirname(src)
print ( " dir1 %s " % dir1)
if (os.path.exists(src) == False):
os.makedirs(dir1)
f1 = open(src, " w " )
f1.write( " line a\n " )
f1.write( " line b\n " )
f1.close()
shutil.copyfile(src, dst)
shutil.copyfile(src, dst2)
f2 = open(dst, " r " )
for line in f2:
print (line)
f2.close()
# 測試復制文件夾樹
try :
srcDir = " d:/download/test "
dstDir = " d:/download/test2 "
# 如果dstDir已經(jīng)存在,那么shutil.copytree方法會報錯!
# 這也意味著你不能直接用d:作為目標路徑.
shutil.copytree(srcDir, dstDir)
except Exception as err:
print (err)
'''
知識點:
* shutil.copyfile:如何復制文件
* os.path.exists:如何判斷文件夾是否存在
* shutil.copytree:如何復制目錄樹
'''
總結(jié):4個函數(shù)
·os.path.dirname(path)
·os.path.exists(path)
·shutil.copyfile(src, dst)
·shutil.copytree(srcDir, dstDir)
繼續(xù)查找其他問題的答案?
相關(guān)視頻回答
點擊加載更多評論>>