文件操作(IO 技术)
文本文件的写入和读取
文件写入
文本文件的写入一般就是三个步骤:
- 创建文件对象
- 写入数据
- 关闭文件对象
示例:
f = open(r"a.txt","a")
s = "i love u\ni am bot\n"
f.write(s)
f.close()
运行结果:
解决中文乱码问题
windows 操作系统默认的编码是 GBK,Linux 操作系统默认的编码是 UTF-8。当我们 用 open()时,调用的是操作系统打开的文件,默认的编码是 GBK。
示例:
f = open(r"b.txt","w")
f.write("我爱你\n你呢\n")
f.close()
运行结果:
解决办法:在文本编辑处将编码格式转换成GBK即可。
write()/writelines()写入数据
write(a):把字符串 a 写入到文件中
writelines(b):把字符串列表写入文件中,不添加换行符
示例:
f = open(r"bb.txt","w",encoding="utf-8")
s = ["你好\n","上午好\n","下午好\n"]
ss = "\n我是字符串aaaa"
f.writelines(s)
f.write(ss)
f.close()
运行结果:
with 语句(上下文管理器)
with 关键字(上下文管理器)可以自动管理上下文资源,不论什么原因跳出 with 块,都能 确保文件正确的关闭,并且可以在代码块执行完毕后自动还原进入该代码块时的现场。
示例:
s = ["你好\n","上午好\n","下午好\n","晚上好\n","i love u\n"]
with open(r"bb.txt","w",encoding="utf-8") as f:
f.writelines(s)
运行结果:
文件的读取
文件的读取一般使用如下三个方法:
- read([size]) 从文件中读取 size 个字符,并作为结果返回。如果没有 size 参数,则读取整个文件。 读取到文件末尾,会返回空字符串。
- readline() 读取一行内容作为结果返回。读取到文件末尾,会返回空字符串。
- readlines() 文本文件中,每一行作为一个字符串存入列表中,返回该列表
示例:
s = ["你好\n","上午好\n","下午好\n","晚上好\n","i love u"]
with open(r"bb.txt","w",encoding="utf-8") as f:
f.writelines(s)
with open(r"bb.txt","r",encoding="utf-8") as f:
print(f.read(2))
print(f.read())
运行结果:
例子:为文本文件每一行的末尾增加行号
with open(r"bb.txt","r",encoding="utf-8") as f:
lines = f.readlines()
lines = [line.rstrip() + "\t#"+str(index+1)+"\n" for index,line in enumerate(lines)]
with open(r"c.txt","w",encoding="utf-8") as f:
f.writelines(lines)
执行前文件内容:
执行后文件内容:
文件任意位置操作
使用seek()方法移动文件指针,通过tell()获得指针位置。
示例:
with open(r"bb.txt","r",encoding="utf-8") as f:
print("文件名是{0}".format(f.name))
print(f.tell())
print("读到的内容是{0}".format(f.readline()))
print(f.tell())
f.seek(0)
print("读到的内容是{0}".format(f.readline()))
运行结果:
CSV 文件的操作
首先通过excel创建表格:
csv文件形式:
读取csv文件数据:
import csv
with open(r"data.csv") as f:
a_scv = csv.reader(f)
headers = next(a_scv)
print(headers)
for row in a_scv:
print(row)
运行结果:
csv文件的写入:
import csv
headers = ["姓名","年龄","编号"]
rows = [("张三",18,1),("李四",19,2),("王五",20,3)]
with open(r"data1.csv","w") as f:
b_csv = csv.writer(f)
b_csv.writerow(headers)
b_csv.writerows(rows)
运行结果:
os 和 os.path 模块
os 模块可以帮助我们直接对操作系统进行操作。我们可以直接调用操作系统的可执行 文件、命令,直接操作文件、目录等等。在系统运维的核心基础。
示例:使用os运行安装好的微信
import os
os.startfile(r"D:\WeChat\WeChat.exe")
运行效果:
os.path的常用方法示例:
import os
import os.path
#判断是否为绝对路径
print(os.path.isabs(r"d.txt"))
#是否为目录
print(os.path.isdir(r"d.txt"))
#是否为文件
print(os.path.isfile(r"d.txt"))
#文件是否存在
print(os.path.exists(r"d.txt"))
#文件大小
print(os.path.getsize(r"d.txt"))
#输出绝对路径
print(os.path.abspath(r"d.txt"))
#输出所在目录
print(os.path.dirname(r"d.txt"))
#得到文件创建时间
print(os.path.getctime(r"d.txt"))
#获得文件最后访问时间
print(os.path.getatime(r"d.txt"))
#获得文件最后修改时间
print(os.path.getmtime(r"d.txt"))
#########################
path = os.path.abspath(r"d.txt")
#返回元组:目录、文件
print(os.path.split(path))
#返回元组:路径、扩展名
print(os.path.splitext(path))
#连成路径
print(os.path.join("aa","bb","cc"))
运行效果:
False
False
True
True
0
D:\pycharmprojects\MyTest\file\d.txt
1603193432.5022268
1603193432.5022268
1603193432.5022268
('D:\\pycharmprojects\\MyTest\\file', 'd.txt')
('D:\\pycharmprojects\\MyTest\\file\\d', '.txt')
aa\bb\cc
walk()递归遍历所有文件和目录
os.walk()方法:
返回一个 3 个元素的元组,(dirpath, dirnames, filenames)。
dirpath:要列出指定目录的路径
dirnames:目录下的所有文件夹
filenames:目录下的所有文件
小例子:使用 walk()递归遍历所有文件和目录。
import os
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
all_files.append(os.path.join(dirpath,dir))
for name in filenames:
all_files.append(os.path.join(dirpath,name))
for file in all_files:
print(file)
运行效果:
D:/pycharmprojects/MyTest/file/test4.py
D:\pycharmprojects\MyTest\file\a.txt
D:\pycharmprojects\MyTest\file\b.txt
D:\pycharmprojects\MyTest\file\bb.txt
D:\pycharmprojects\MyTest\file\c.txt
D:\pycharmprojects\MyTest\file\d.txt
D:\pycharmprojects\MyTest\file\data.csv
D:\pycharmprojects\MyTest\file\data1.csv
D:\pycharmprojects\MyTest\file\test1.py
D:\pycharmprojects\MyTest\file\test2.py
D:\pycharmprojects\MyTest\file\test3.py
D:\pycharmprojects\MyTest\file\test4.py
shutil 模块(拷贝和压缩)
import shutil
import zipfile
#复制文件
shutil.copyfile("a.txt","a_copy.txt")
#压缩
z = zipfile.ZipFile("a.zip","w")
z.write("a.txt")
z.write("b.txt")
z.close()
#解压缩
z2 = zipfile.ZipFile("a.zip","r")
z2.extractall("d;/pycharmproject/MyTest")
z2.close()