10.1 从文件中读取数据
10.1.1 读取整个文件
先创建一个文件,包含精确到小数点后30位的圆周率值,且在小数点后每10位处都换行:
python">3.1415926535
8979323846
2643383279
下面的程序打开并读取这个文件,再将其内容显示在屏幕上:
python">with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
函数open()
接受一个参数:要打开文件的名称,Python在当前执行的文件所在目录中查找指定的文件。函数open()
返回一个表示pi_digits.txt的对象,Python将这个对象存储在后面的变量file_object
中。关键字with
在不再需要访问文件后将其关闭,使用这种结构,可以让Python去确定在合适的时候自动将其关闭。
上面代码的输出是:
python">3.1415926535
8979323846
2643383279
read()
到达文件末尾时返回一个空字符串,显示出来就是一个空行,使用rstrip()
将其去除:
python">with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
3.1415926535
8979323846
2643383279
10.1.2 文件路径
文件路径有绝对
路径和相对
路径两种。相对路径的位置是相对于当前运行的程序所在目录,例如,假设程序文件存储在文件夹Python_work中,文本文件存储在文件夹Python_work的子文件夹text_files中,相对路径可编写为:
python">## Linux 和 OS X
with open('text_files/filename.txt') as file_object:
## Windows
with open('text_files\filename.txt') as file_object:
绝对路径指的是向Python传递一个完整的文件路径。
10.1.3 逐行读取
使用for
循环以每次一行的方式检查文件:
python">with open('pi_digits.txt') as file_object:
for line in file_object:
print(line)
3.1415926535
8979323846
2643383279
出现空白行的原因是每一行末尾都有一个换行符,而print语句也会加上一个换行符,在print语句中使用rstrip()
来消除空白行:
python">with open('pi_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())
3.1415926535
8979323846
2643383279
10.1.4 创建一个包含文件各行内容的列表
要在with代码块外访问文件的内容,可在with代码块内使用方法readlines()
将文件的各行存储在一个列表中:
python">with open('pi_digits.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
10.1.5 使用文件的内容
使用读取上述文件中的数字,使它们之间没有空格:
python">with open('pi_digits.txt') as file_object:
lines = file_object.readlines()
pi_string = ""
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
10.1.6 包含一百万位的大型文件
略。
10.1.7 圆周率值中包含你的生日吗
略。
10.2 写入文件
10.2.1 写入空文件
python">filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
第二个实参‘w’
表示要以写入
模式打开文件,类似的模式有读取模式('r‘
),附加模式(’a‘
)或能让你能够读取和写入文件的模式(’r+‘
),如果忽略,Python将以默认的只读模式打开文件。以(’w‘)模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
注意:Python只能将字符串写入文件,要将数值数据存储到文本文件,必须先使用函数str()
将其转换为字符串格式。
10.2.2 写入多行
python">filename = 'programming,txt'
with open(filename,'w') as file_object:
file_object.write("123\n")
file_object.write("456\n")
10.2.3 附加到文件
以附加模式’a‘
打开文件时,不会清空文件内容,写入文件的行都将添加到文件末尾,如果指定文件不存在,创建文件。
python">with open(filename,'a') as file_object:
file_object.write("123\n")
10.3 异常
Python使用被称为异常
的特殊对象来管理执行程序期间发生的错误,异常是使用try-except
代码块处理的。
10.3.1 处理ZeroDivisionError异常
python">>>> 5/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
10.3.2 使用try-except代码块
python">>>> try:
... print(5/0)
... except ZeroDivisionError:
... print("You can't divide by zero!")
...
You can't divide by zero!
10.3.3 使用异常避免崩溃
10.3.4 else代码块
python">while True:
first_number = input("\nFirst number:")
if first_number == 'q':
break
second_number == input("Second number:")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
First number:5
Second number:0
You can't divide by 0!
First number:5
Second number:2
2.5
First number:q
10.3.5 处理FlieNotFoundError异常
python">try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry,the file" + filename + "does not exist"
print(msg)
10.3.6 分析文本
统计文件中单词的个数,可以用split()
方法。
python">>>> title = "Alice in Wonderland"
>>> title.split()
['Alice', 'in', 'Wonderland']
>>> len(title.split())
3
10.4 存储数据
模块json
让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载文件中的数据。
10.4.1 使用json.dump()和json.load()
使用函数json.dump()
将数字列表存储到文件numbers.json中。
python">import json
numbers = [2,3,5,7,11]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
再编写一个程序,使用json.load()
读取numbers.json中的信息,存储到numbers变量中,打印输出:
python">import json
filename = 'numbers.json'
with open(filename,'r') as f_obj:
numbers = json.load(f_obj)
print(numbers)
[2, 3, 5, 7, 11]