python学习9:文件和异常
1 从文件中读取数据
要使用文本文件中的信息,首先需要将信息读取。为此可以一次性读取文件的全部内容,或者以每次一行的方式逐步读取。
1.1 读取整个文件
在目录下保存一个txt文件。
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
结果:
3.1415926535
8979323846
2643383279
- 函数
open()
接收一个参数:要打开文件的名称。python在当前执行的文件所在的目录中查找指定的文件,返回一个表示文件的对象。 - 关键字
with
在不再需要访问文件后将其关闭。 - 方法
read()
读取文件的全部内容,将其作为一个字符串赋给变量,但到达文件末尾时返回一个空字符串,即空行,可使用rstrip()
删去。
1.2 文件路径
绝对文件路径:将文件在计算机中的准确位置告诉python,一般比较长,因此将其赋给一个变量,再将该变量传递给open()
。
file_path = 'D:\\pycharm\\python实践\\文件和异常\\pi_digits.txt'
with open(file_path) as file_object:
- 如果在文件路径中直接使用反斜杠比较容易引发错误,因此需要对每个反斜杠进行转义,如
\\
。
1.3 逐行读取
要以每次一行的方式检查文件,可对文件对象使用for循环。
file_path = 'D:\\pycharm\\python实践\\文件和异常\\pi_digits.txt'
with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
结果:
3.1415926535
8979323846
2643383279
1.4 创建一个包含文件各行内容的列表
使用关键字with
时,open()
返回的文件对象只在with代码块内可用。如果要在with外访问文件内容的话,可以在with代码块内将文件的各行存储在一个列表中。
file_path = 'D:\\pycharm\\python实践\\文件和异常\\pi_digits.txt'
with open(file_path) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
- 方法
readlines()
从文件中读取每一行,并将其存储在一个列表中。
1.5 使用文件的内容
file_path = 'D:\\pycharm\\python实践\\文件和异常\\pi_digits.txt'
with open(file_path) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
结果:
3.141592653589793238462643383279
32
2 写入文件
2.1 写入空文件
要将文本写入文件,在调用open()
时需要提供另一个实参,告诉python要写入打开的文件。
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
- 调用
open()
时提供了两个实参。第一个实参是要打开的文件的名称,第二个实参('w')
告诉python,要以写入模式打开这个文件。模式有:读取('r')
、写入('w')
、附加(a)
、读写(r+)
- 如果要写入的文件不存在,
open()
将自动创建它,如果存在,python将在返回文件对象前清空该文件的内容。 - python只能将字符串写入文本文件,要将数值数据存储到文本文件中,必须使用函数
str()
将其转化为字符串格式。
2.2 写入多行
函数write()
不会在写入的文本末尾添加换行符,因此如果在写入多行时没有指定换行符,文件看起来不会像希望的那样:
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
结果:
I love programming.I love creating new games.
因此需要在调用write()
时包含换行符。
2.3 附加到文件
如果要给文件添加内容,而不是覆盖原有的内容,可以以附加模式打开文件。这样不会清空原有的文件,而是将写入的文件的行添加到文件末尾。
with open(filename, 'a') as file_object:
3 异常
使用try-except
代码块时,即便出现异常,程序也将继续运行,显示编写的友好的错误信息,而不是traceback。
try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
结果:
You can't divide by zero!
4 存储数据
4.1 使用json.dump()和json.load()
使用json模块来存储数据,可以将简单地python数据结构转储到文件中,并在程序再次运行时加载文件中的数据。(json格式可以与其他编程语言分享)
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
- 函数
json.dump()
接收两个实参:要存储的数据,可用于存储数据的文件对象。
import json
filename = 'numbers.json'
with open(filename, 'r') as f:
numbers = json.load(f)
print(numbers)
函数json.load()
加载存储在numbers.json中的信息,并将其赋给numbers。