第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
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)

  

 

猜你喜欢

转载自www.cnblogs.com/wssys/p/10201224.html