文件通常用于存储数据或应用系统的参数。
文件的创建
文件的打开和创建可以使用open()函数。
r:以只读的方式打开文件
r+:以读写的方式打开文件
w:以写入的方式打开文件,先删除文件原有的内容,再重新写入新的内容。如果文件不存在,则创建一个新的文件。
w+:以读写的方式打开文件,先删除文件原有的内容,再重新写入新的内容。如果文件不存在,则创建一个新的文件。
a:以写入的方式打开文件,在文件的末尾追加新的内容。如果文件不存在,创建一个新的文件。
a+:以读写的方式打开文件,在文件的末尾追加新的内容。如果文件不存在,则创建一个新的文件。
文件处理一般分为以下三个步骤:
(1)创建并打开文件,使用file()函数返回一个file对象
(2)调用file对象的read(),write()等方法处理文件
(3)调用close()关闭文件,释放file对象占用的资源。
#创建文件
context = "hello python"
f = open('hello.txt', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close()
文件的读取
按行读取的方式readline()
readline()每次读取文件中的一行,需要使用永真表达式循环读取文件。但当文件指针移动到文件末尾时,依然使用readline()读取文件将会出现错误。因此程序中需要添加一个判断语句,判断文件指针是否移动到文件尾部,并且通过该语句中断循环。
f = open("hello.txt")
while True:
line = f.readline()
if line:
print(line)
else:
break
f.close()
多行读取文件readlines()
f = open("hello.txt")
lines = f.readlines()
for line in lines:
print(line)
f.close()
一次性读取read()
f = open("hello.txt")
context = f.read()
print(context)
f.close()
通过控制read()参数,返回指定字节的内容。
f = open("hello.txt")
context = f.read(5) # 读取文件前五个字节的内容
print(context)
print(f.tell()) # 返回文件对象当前指针位置
context = f.read(5) # 继续读取五个字节内容
print(context)
print(f.tell()) # 输出文件当前指针位置
f.close()
file对象内部将记录文件指针的位置,以便下次操作。只要file对象没有执行close()方法,文件指针就不会释放。
文件的写入
writelines()操作
f = open("hello.txt", "w+")
f.writelines("hello python,hello china")
f.close()
f = open("hello.txt", "a+")
f.writelines("hi python,hi china")
f.close()
writelines()写文件的速度更快。写少量字符串可以使用write()
文件的删除操作
文件的删除操作需要使用os模块和os.path模块。文件的删除操作需要调用remove()函数实现。删除文件之先需要判断文件是否存在,存在则删除,否则不进行任何操作。
import os
if os.path.exists("hello.txt"):
os.remove("hello.txt")
文件的复制
文件的复制需要使用write()和read()方法。
src = open('hello.txt', 'w')
src.write("hello python!hello world!")
src.close()
src = open("hello.txt", "r")
dst = open("hello2.txt", "w")
dst.write(src.read())
src.close()
dst.close()
文件的重命名
os模块的rename()函数可以对文件或目录进行重命名。
import os
li = os.listdir(".") #listdir()返回当前目录的文件列表,"."表示当前目录
print(li)
if "hello.txt" in li:
os.rename("hello.txt", "hi.txt")
修改文件的后缀名需要使用rename()函数,和字符串查找的函数
# 修改文件后缀名
import os
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos+1:] == "txt":
newname = filename[:pos+1]+"html"
os.rename(filename,newname)
文件内容的搜索和替换
#文件的查找
import re
file = open("hello.txt", "r")
count = 0
for s in file.readlines():
print(s)
li = re.findall("hello", s)
print(li)
if len(li) > 0:
count = count + li.count("hello")
print("hello的个数{}".format(count))
file.close()
#文件的替换 把hello.txt里的hello改为hi写入hello2.txt
f1 = open("hello.txt", "r")
f2 = open("hello2.txt", "w")
for s in f1.readlines():
f2.writelines(s.replace("hello", "hi"))
f1.close()
f2.close()