目录
一、从文件中读取数据
1、读取整个文件
with open('test.txt') as file_object:
contents=file_object.read()
print(contents)
2、文件路径
相对路径和绝对路径。
3、逐行读取
filename='test.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
这个时候输出的内容存在空白行,可以这么处理:
filename='test.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
4、创建一个包含文件各行内容的列表
filename='test.txt'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
5、使用文件的内容
读取文本文件时,Python将其中的所有文本都解读为字符串。
6、读取一百万位的大型文件
对于数据量,Python没有任何限制,只要系统的内存足够多,多少数据都可以处理。
二、写入文件
1、写入空文件
filename='test.txt'
with open(filename,'w') as file_object:
file_object.write("I love Python!")
Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
2、写入多行
filename='test.txt'
with open(filename,'w') as file_object:
file_object.write("I love Python!")
file_object.write("I love you!")
'''文件只有一行'''
filename='test.txt'
with open(filename,'w') as file_object:
file_object.write("I love Python!\n")
file_object.write("I love you!\n")
3、附加文件
filename='test.txt'
with open(filename,'a') as file_object:
file_object.write("I love Python!")
file_object.write("I love you!")
'''在文件后追加内容'''
三、异常
1、处理ZeroDivisionError异常
2、使用try-except代码块
3、使用异常避免崩溃
4、else代码块
5、处理FileNotFoundError异常
6、分析文本
7、使用多个文件
四、存储数据
1、使用json.dump()和json.load()
函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。使用json.load()读取列表的数字。
import json
numbers=[2,3,4,5,6]
file_name='number.json'
with open(file_name,'w' )as file_object:
json.dump(numbers,file_object)
读取:
import json
file_name='number.json'
with open(file_name)as file_object:
numbers=json.load(file_object)
print(numbers)
2、保存和读取用户生成的数据
3、重构
代码可以正确地运行,但可以做进一步的改进——将代码划分为一系列完成具体工作的函数,这样的过程被称为重构。
文章若有错误,请指正。