第7章 使用Python处理文件

本章的知识点:

1、文件的创建、读写和修改;

2、文件的复印、删除和重命名;

3、文件内容的搜索和替换;

4、文件的比较;

5、配置文件的读写;

6、目录的创建和遍历;

7、文件和流;

7.1 文件的常见操作

7.1.1 我呢见的创建

## 创建文件
context = '''hello world'''
f = open('hello.txt', 'w')  # 打开文件
f.write(context)  # 把字符串写入文件
f.close()  # 关闭文件
1)按行读取方式readline
## 使用readline()读文件
f = open("hello.txt")  # 打开文件
while True:
    line = f.readline()
    if line:
        print (line)
    else:
        break
f.close()  # 关闭文件
# 输出:hello world
2)多行读取方式readlines()
## 使用readlines()读文件
f = file('hello.txt')
lines = f.readlines()
for line in lines:
    print (line)
f.close()
3) 一次性读取方式read()
## 使用read读取文件
f = open("hello.txt")
context = f.read()
print (context)
f.close()
# 输出:hello world
# hello China
f = open("hello.txt")
context = f.read(5)
print (context)
print (f.tell())
context = f.read(5)
print (context)
print (f.read())
f.close()
# 输出:hello
# 5
#  worl
# d
# hello China

7.1.3 文件的写入

## 使用writelines()写文件
f = file("hello.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()
## 追加新的内容到文件
f = file("hello.txt", "a+")
new_context = "goodbye"
f.write(new_context)
f.close()

7.1.4 文件的删除

import os
file("hello.txt", "w")
if os.path.exists("hello.txt"):
    os.remove("hello.txt")

7.1.5 文件的复制

## 使用read()、write()实现复制
## 创建文件hello.txt
src = open("hello.txt","w")
li = ["hello world\n","hello China\n","nihao"]
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模块实现文件的复制
import shutil
shutil.copyfile("hello.txt", "hello2.txt")
shutil.move("hello.txt","../")
shutil.move("hello2.txt","hello3.txt")

7.1.6 文件的重命名

## 修改文件
import os
li = os.listdir(".")
print (li)
if "hello.txt" in li:
    os.rename("hello.txt", "hi.txt")
elif "hi.txt" in li:
    os.rename("hi.txt", "hello.txt")
# 输出:['hello.txt', 'hello2.txt', 'hello3.txt', '内容.py', '本章的知识点']
## 修改后缀
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)

7.1.7 文件内容的搜索和替换

## 文件的查找
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()
# 输出:查找到2个hello
## 文件的替换
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()

7.1.8 文件的比较

import difflib
f1 = open("hello.txt", "r")
f2 = open("hi.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]))

7.1.9 配置文件的访问

## 配置文件
import configparser
config = configparser.ConfigParser()
config.read("ODBC.ini")
sections = config.sections()
print ("配置块:", sections)
o = config.options("ODBC 32 dit Data Sources")
print ("配置项", o)
v = config.items("ODBC 32 dit Data Sources")
print ("内容", v)
## 根据配置块和配置项返回内容
access = config.get("ODBC 32 dit Data Sources", "MS Access Database")
print (access)
excel = config.get("ODBC 32 dit Data Sources", "Excel Files")
print (excel)
dBASE = config.get("ODBC 32 dit Data Sources", "dBASE Files")
print (dBASE)
## 写配置文件
import configparser
config = configparser.ConfigParser()
config.add_section("ODBC Driver Count")
config.set("ODBC Driver Count", "count", 2)
f = open("ODBC.ini","a+")
config.writte(f)
f.close()
## 修改配置文件
import configparser
config = configparser.ConfigParser()
config.read("ODBC.ini", "r+")
config.set("ODBC Driver Count", 3)
f = open("ODBC.ini", "r+")
config.write(f)
f.close()

7.2 目录的常见操作

7.2.1 创建和删除目录

import os
os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello/world")
os.removedirs("hello/world")

7.2.2 目录的遍历

## 递归遍历目录
import os
def VisitDir(path):
    li = os.listdir(path)
    for p in li:
        pathname = os.path.join(path, p)
        if not os.isfile(pathname):
            VisitDir(pathname)
        else:
            print (pathname)
if __name__ == "__main__":
    path = r"D:\Python\零基础学 python\第7章 使用Python处理文件\hello.txt"
    VisitDir(path)
import os
def VisitDir(path):
    for root,dirs,files in os.walk(path):
        for filepath in files:
            print (os.path.join(root, filepath))
if __name__ == "__main__":
    path = r"D:\Python\零基础学 python\第7章 使用Python处理文件\07"
    VisitDir(path)

7.3 文件和流

7.1.3 Python的流对象

#         1)stdin
import sys
sys.stdin = open("hello.txt", "r")
for line in sys.stdin.readlines():
    print (line)
# 输出:hello world
# 
# hello China
#             2)stdout
import sys
sys.stdout = open(r"./hello.txt", "a")
print ("goodbye")
sys.stdout.close()
import sys,time
sys.stderr = open("record.log", "a")
f = open(r"./hello.txt","r")
t = time.strftime("%Y-%m-%d %X",time.localtime())
context = f.read()
if context:
    sys.stderr.write(t + "" + context)
else:
    raise Exception, t + "异常信息"

7.3.2 模拟Java的输入、输出流

## 文件输入流
def FileInputStream(filename):
    try:
        f = open(filename)
        for line in f:
            for byte in line:
                yield byte
    except StopIteration, e:
        f.close()
        return
## 文件输出流
def FileOutputStream(inputStream, filename):
    try:
        f = open(filename, "w")
        while True:
            byte = inputStream.next()
            f.write(byte)
    except StopIteration, e:
        f.close()
        return
if __name__ == "__main__":
    FileInputStream(FileInputStream("hello.txt"), "hello2.txt")

7.4 文件处理示例--文件属性浏览程序

def showFileProperties(path):
    '''显示文件的属性。包括路径、大小、创建日期、最后修改时间,最后访问时间'''
    import time,os
    for root,dirs,files in os.walk(path, True):
        print ("位置:" + root)
        for filename in files:
            state = os.stat(os.path.join(root, filename))
            info = "文件名:" + filename + ""
            info = info + "大小:" + ("%d" % state[-4]) + ""
            t = time.strftime("%Y-%m-%d %X", time.localtime(state[-1]))
            info = info + "创建时间:" + t + ""
            t = time.strftime("%Y-%m-%d %X", time.localtime(state[-2]))
            info = info + "最后修改时间:" + t + ""
            t = time.strftime("%Y-%m-%d %X", time.localtime(state[-3]))
            info = info + "最后访问时间:" + t + ""
            print (info)
if __name__ == "__main__":
    path = r"D:\Python\零基础学 python\第7章 使用Python处理文件\07"
    showFileProperties(path)

7.6 习题

文件test.txt中包含以下内容:

posted @ 2018-12-31 00:57  无声胜有声  阅读(184)  评论(0)    收藏  举报