前言:所有的操作都需要先导入 import os 和 import shutil
1、简单说明
os 官方说明文档:https://docs.python.org/zh-cn/3/library/os.html?highlight=os
shutil 官方说明文档:https://docs.python.org/zh-cn/3.6/library/shutil.html?highlight=shutil#module-shutil
os文件部分的简单介绍:
os.getcwd() 方法用于返回当前工作目录
os.remove() 方法用于删除指定路径的文件。注意不能是目录,不然将抛出OSError。
os.rename(src,dst) 方法用于命名文件或目录。src 要修改的目录名,dst修改后的目录名
os.path 模块主要用于文件的属性获取,os.path.exists用于判断文件是否存在
os.makedirs() 方法用于创建文件夹
shutil 部分简单介绍:
shutil.copy(src,dst) 方法用于复制文件
shutil.copytree(src,dst) 方法用于复制目录
shutil.rmtree(src) 方法用于删除目录
shutil.move(源文件,指定目录) 方法用于移动文件
压缩与解压 使用zipfile或者tarfile
2、使用shutil.copytree复制时,出现“[WinError 183] 当文件已存在时,无法创建该文件。”的问题。
只要复制与被复制文件夹中含有相同文件时,就会出现这个错误。要解决这个问题,可以使用例子中的CopyFolder方法
例子:
# coding: utf-8
#Created by yeliang23 on 2018/6/19.
import sys
import os
import shutil
# -------- 文件夹操作 --------
#判断文件夹是否存在
def isExistsFolder(in_dir):
isExists=os.path.exists(in_dir) #判断文件夹是否存在
if isExists:
print('文件夹'+in_dir+'存在')
return 'true'
else:
print('文件夹'+in_dir+'不存在')
return 'false'
#创建文件夹
def CreateFolder(in_dir):
print('创建'+in_dir+'文件夹')
isExists=os.path.exists(in_dir)
if not isExists: #不存在则创建
print('创建'+in_dir+'文件夹成功')
else:
print(in_dir+'文件夹已存在')
#删除文件夹
def DeleteFolder(in_dir):
print('删除'+in_dir+'文件夹')
isExists=os.path.exists(in_dir) #判断文件夹是否存在
if not isExists: #不存在则不需要删除
print('找不到'+in_dir+'文件夹,无法删除')
else:
shutil.rmtree(in_dir)
print(in_dir+'文件夹已删除')
# 复制文件夹
# write_exists True为覆盖,False为跳过
def CopyFolder(in_dir, out_dir, write_exists=False, tabnum=0):
if(0 == tabnum):
print('文件目录复制模式为: %s' % ('覆盖' if write_exists else '跳过'))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
copy_file_counts = 0
copy_dir_counts = 0
for f in os.listdir(in_dir):
in_f = os.path.join(in_dir, f)
out_f = os.path.join(out_dir, f)
if os.path.isfile(in_f):
copy_file_counts += 1
if write_exists or not os.path.exists(out_f): # 文件不存在
open(out_f, "wb").write(open(in_f, "rb").read())
if os.path.isdir(in_f):
copy_dir_counts += 1
CopyFolder(in_f,out_f,write_exists,tabnum+1)
#---------- 文件修改操作 ----------
#按行读取文件
#Num为需要读取的行
#如只读取第五行,则填写'5'
#如读取1到5行,则填写'1-5'
#如读取全部则填写'All'
#注意如果文件过大,不能使用此方法。
#要使用linecache来读取,linecache.getline(filename,linenum)读取文件的某一行,linecache.getlines(filename)读取文件
def ReadFile(in_dir,Num):
print('读取'+in_dir+'文件的第'+Num+'行')
file_data=""
try:
isExists=os.path.exists(in_dir) #判断文件是否存在
if not isExists:
print('找不到'+in_dir+'文件,无法读取')
else:
file = open(in_dir, "r", encoding="utf-8")
if Num=='All':
for line in file:
file_data=file_data+line
else:
if '-' in Num:
list=Num.split('-',2)
NumStart=list[0]
NumEnd=list[1]
else:
NumStart=Num
NumEnd=Num
i=0
for line in file:
i=i+1
if int(NumStart)<= i <=int(NumEnd):
file_data=file_data+line
print(in_dir+'文件已读取')
except Exception as e:
print('文件读取失败:'+str(e))
finally:
file.close()
return file_data
#写入文件
#在文件的末尾新增字符串
def WriteFile(in_dir,AddStr):
print('向'+in_dir+'文件写入'+AddStr)
try:
isExists=os.path.exists(in_dir) #判断文件夹是否存在
if not isExists:
print('找不到'+in_dir+'文件,无法写入')
else:
file = open(in_dir, "a", encoding="utf-8") #w是清除原有文本然后写入,a是在文本后面新增
file.write('\n'+AddStr)
print(AddStr+'已写入'+in_dir)
except Exception as e:
print('文件写入失败:'+str(e))
finally:
file.close()
#替换文件中的字符串(替换失败,待会再修改)
def ReplaceFile(in_dir,OldStr,NewStr):
print('替换'+in_dir+'文件中的'+OldStr+'为'+NewStr)
file_data=''
isExists=os.path.exists(in_dir) #判断文件夹是否存在
if not isExists:
print('找不到'+in_dir+'文件,无法替换')
else:
with open(in_dir, "r", encoding="utf-8") as file:
for line in file:
if OldStr in line:
line = line.replace(OldStr,NewStr)
file_data = file_data+line
with open(in_dir,"w",encoding="utf-8") as file:
file.write(file_data)
print(in_dir+'中的'+OldStr+'已替换为'+'NewStr')
if '__main__' == __name__:
root = 'd:/test/'
copy_in = root+'a'
copy_out = root+'b'
Write_file = copy_in+'/build.gradle'
CopyFolder(copy_in,copy_out,write_exists=True)
print('复制完毕')
DeleteFolder(copy_out+"/src")
print('删除完毕')
WriteFile(Write_file,"aaa")
print('写入完毕')
r=ReadFile(Write_file,"5-7")
print('读取到\n'+r)
ReplaceFile(Write_file,"aaa","abcdefg")
print('替换完毕')