Python中文件的读写
定义
在python中读写的时候,有两种方式:文本方式和二进制的方式
注意:无论如何处理都要关闭文件
打开
open()函数
在读取文件之前,我们先要打开文件,我们需要用到open函数
open函数的定义
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
file:代表的是一个文件:字符串,代表文件以及文件所在路径的字符串
mode(可改):最重要的参数,打开文件的方式
encoding:代表编码方式
打开文件的方式
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
r:只读模式
只读不可写
w:只写模式
只写不可读,且每次写入会清除之前的内容
a:追加模式
只写不可读,写入到光标所在位置,不会清除之前的内容
r+:读写模式
先读后写,不会清除原内容
如果先写后读,写入的内容会覆盖
w+:写读模式
先写后读,清除原内容
a+:追加写读模式
追加在末尾,不会清除原内容
关闭
close()
我们在打开文件执行完自己想要完成的操作后,必须关闭文件
file_obj = open("python.txt")
str_data = file_obj.read()
file_obj.close()
print(str_data)
异常处理
在使用close()方法关闭文件的时候,如果出现异常,会导致文件无法关闭。
我们必须使用异常处理的方法来解决这个问题
with()
如果每次都使用异常处理的方法,太过繁琐。
with()函数可以帮助我们解决这个问题,with()函数帮助我们自动关闭文件
with open("python.txt", 'r') as file_obj:
print(file_obj.read())
文件 读(Read) 操作
read()
读取文件的所有内容放入字符串中
例如,我们有一个名字为 hello.txt 的文件,文件里内容为 hello world
with open("hello.txt", 'r', encoding='utf-8') as read_obj:
print(read_obj.read())
print(read_obj.read(2))
运行结果
hello world
he
readline()
读取一行的内容
例如,我们有一个名字为 hello.txt 的文件,文件里内容第一行为 hello 第二行为 world
with open("hello.txt", 'r', encoding='utf-8') as read_obj:
print(read_obj.readline())
print(read_obj.readline(2))
运行结果
hello
wo
readlines()
读取文件中所有内容
例如,我们有一个名字为 hello.txt 的文件,文件里内容每一行为helloworld的一个字符
with open("hello.txt", 'r', encoding='utf-8') as read_obj:
print(read_obj.readlines())
运行结果
['h\n', 'e\n', 'l\n', 'l\n', 'o\n', 'w\n', 'o\n', 'r\n', 'l\n', 'd']
我们可以看到读取的内容都有一个换行符\n
文件 写(Write) 操作
write()
把内容写入文件
例如,我们有一个名字为 hello.txt 的文件,文件里内容为空,我们要写入helloworld
with open("hello.txt", 'w', encoding='utf-8') as write_obj:
write_obj.write("helloworld")
运行完成, hello.txt 的内容为 helloworld
writelines()
把多行内容写入文件,参数可以是一个可迭代的对象
例如,我们有一个名字为 hello.txt 的文件,文件里内容为空,我们要写入列表list_data
with open("hello.txt", "w", encoding="utf-8") as write_obj:
list_data = ['h', 'e', 'l', 'l', 'o']
write_obj.writelines(list_data)
运行完成, hello.txt 的内容为 hello
练习
读写文件:
a.以写的方式打开文件stu_info.txt并向文件中写入(姓名-性别-年龄):每个一行
zhangsan-male-20
lisi-female-21
wangwu-male-20
with open("stu_info.txt","at",encoding="utf-8") as write_obj:
write_obj.write("\nzhangsan-male-20")
write_obj.write("\nlisi-female-21")
write_obj.write("\nwangwu-male-22")
b.以读的方式打开文件stu_info.txt,读取文件的每一行内容,并格式化输出,输出格式:居中对齐
姓名 性别 年龄
zhangsan male 20
lisi female 21
wangwu male 22
with open("stu_info.txt","rt",encoding="utf-8") as read_obj:
data_list = read_obj.readlines()
print(f"{'姓名':^10}\t{'性别':^10}\t{'年龄':^10}\t")
for data in data_list:
data = data.strip()
data = data.split("-")
print(f"{data[0]:^10}\t{data[1]:^10}\t{data[2]:^10}\t")
运行结果
姓名 性别 年龄
zhangsan male 20
lisi female 21
wangwu male 22