1. 程式人生 > >python3的檔案操作2

python3的檔案操作2

檔案的複製
複製函式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)