文件的复制
复制函数copyfile():
# 使用read()、write()实现拷贝
# 创建文件hello.txt
src = open("hello.txt", "w")
li = ["hello world\n", "hello China\n"]
src.writelines(li)
src.close()
# 把hello.txt拷贝到hello2.txt
src = open("hello.txt", "r")
dst = open("hello2.txt", "w")
dst.write(src.read())
src.close()
dst.close()
使用shutil模块实现文件的复制:
# shutil模块实现文件的复制
import shutil
shutil.copyfile("hello.txt","hello2.txt")
shutil.move("hello.txt","../")
shutil.move("hello2.txt","hello3.txt")
说明,先是把hello的内容复制给hello2,然后调用move(),把hello复制到当前目录的父目录,然后删除hello,再调用move(),把hello2移动到当前目录,并命名为hello3。
文件的重命名:
# 修改文件名
import os
li = os.listdir(".")
print (li)
if "hello3.txt" in li:
os.rename("hello3.txt", "hi.txt")
elif "hi.txt" in li:
os.rename("hi.txt", "hello3.txt")
实际应用中,通常需要把某一类文件修改为另一种类型,如下,将html修改为htm:
# 修改后缀名
import os
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos + 1:] == "html":
newname = filename[:pos + 1] + "htm"
os.rename(filename,newname)
此段代码可以进行优化下:
import os
files=os.listdir(".")
for filename in files:
li=os.path.splitext(filename)
if li[1]==".html":
newname=li[0]+".htm"
os.rename(filename,newname)
文件内容的搜索与替换
我们创建一个hello.txt,如下:
hello world
hello hello China
下面的代码将统计其中hello的个数:
# 文件的查找
import re
f1 = open("hello.txt", "r")
count = 0
for s in f1.readlines():
li = re.findall("hello", s)
if len(li) > 0:
count = count + li.count("hello")
print ("查找到" + str(count) + "个hello")
f1.close()
将hello全部替换为hi
# 文件的替换
f1 = open("hello.txt", "r")
f2 = open("hello2.txt", "w")
for s in f1.readlines():
f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()
接下来看看文件的比较:
import difflib
f1 = open("hello.txt", "r")
f2 = open("hello2.txt", "r")
src = f1.read()
dst = f2.read()
print (src)
print (dst)
s = difflib.SequenceMatcher( lambda x: x == "", src, dst)
for tag, i1, i2, j1, j2 in s.get_opcodes():
print ("%s src[%d:%d]=%s dst[%d:%d]=%s" % \
(tag, i1, i2, src[i1:i2], j1, j2, dst[j1:j2]))
遍历目录:
# 递归遍历目录
import os
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
print (pathname)
if __name__ == "__main__":
path = r"E:\daima\ch07"
VisitDir(path)