1.读取整个文件
创建一个名为pi_digits.txt的文件,文件内容 如下:
3.1415926535
8979323846
2643383279
在程序中打开并读取这个文件,再将内容显示到屏幕上:
file_reader.py
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
执行结果为:
在这个程序中,第一行代码做了大量的工作。我们先看函数open( )。要以任何方式使用文件——哪怕仅仅是打印其内容,都要先打开文件,这样才能访问它。函数open( )接受一个参数:要打开的文件的名称。python在当前执行的文件所在的目录中查找指定的文件。函数open( )返回一个表示文件的对象。python将这个对象存储在我们将在后面使用的变量中。
关键字with在不需要访问文件后将其关闭。在这个程序中,我们调用了open(),但没有调用close();也可以通过open()和close()来打开和关闭文件,但这样做时,如果程序存在bug,导致close()语句未执行,文件将不会关闭。这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早的调用close(),会发现需要使用文件时,文件已经关闭(无法访问),这会导致更多的错误。并非在任何情况下都能轻松确定关闭文件的恰当时机,但通过使用前面所示的结构,可让python去确定:我们只管打开文件,并在需要时使用它,python自会在何时的时候自动将其关闭。
方法read()读取这个文件的全部内容,并将其作为一个长长的字符串存储在变量contents中。read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行。要删除末尾的空行,可在print语句中使用rstrip():
print(contents.rstrip())
2.文件路径
当将类似pi_digits.txt这样的简单文件名传递给函数open()时,python将在当前执行的文件(即.py程序文件)所在的目录中查找文件。
根据我们组织文件的方式,有时可能需要打开不在程序文件所属目录中的文件。例如,我们可能将程序文件存储在了文件夹python_work中,而在文件夹python_work中,有一个名为txt_files的文件夹,用于存储程序文件操作的文本文件。虽然文件夹txt_files包含在文件夹python_work中,但仅向open()传递位于该文件夹中的问价的名称也不可行,因为python只在文件夹python_work中查找,而不会在其子文件夹txt_files中查找。要让python打开不与程序文件位于同一个目录中的文件,需要提供文件路径,它让python到系统的特定位置去查找。
由于文件夹txt_files位于文件夹python_work中,因此可以使用相对文件路径来打开该文件夹中的文件。相对文件路径让python到指定的位置去查找,而该位置是相对于当前运行的程序所在目录的。在Linux和OS X中,可以这样编写代码:
with open('txt_files/filename.txt') as file_object:
在Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/):
with open('txt_files\filename.txt') as file_object:
我们还可以将文件在系统中的准确位置告诉python,这样就不用关系当前运行的程序存储在什么地方了。这称为绝对文件路径。在相对路径行不通时,可以使用绝对路径。例如,如果txt_files并不在文件夹python_work中,而是在文件夹
other_files中,则向open()传递路径’txt_files\filename.txt’行不通,因为python只在问价夹python_work中查找该位置。为明确的指出我们希望python到哪里去找,需要提供完整的路径。
绝对路径通常比相对路径更长,因此将其存储在一个变量中,再将该变量传递给open()。在Linux和OS X中,绝对路径类似于下面这样:
file_path = '/home/ehmattes/other_files/text_files/file_name.txt'
with open(file_path) as file_object:
而在Windows系统中,它们类似于下面这样:
file_path = 'C:\Users\ehmattes\other_files\text_files\file_name.txt'
with open(file_path) as file_object:
通过使用绝对路径,可读取系统任何地方的文件。就目前而言,最简单的做法是,要么将数据文件存储在程序文件所在的目录,要么将其存储在程序文件所在目录下的一个文件夹(如text_files)中。
注意:Windows系统有时能够正确的解读文件路径中的斜杠。如果你使用的是Windows系统,且结果不符合预期,请确保在文件路径中使用的是反斜杠。另外,由于反斜杠在python中被视为转义标记,为在Windows中确保万无一失,应以原始字符串的方式指定路径,即在开头的单引号前加上r。
3.逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
执行结果为:
我们打印每一行时,发现空白更多了。为何会出现这些空白行呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一个来自print语句。要清除这些多余的空白行,可在print语句中使用rstrip():
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
4.创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:我们可以立即处理文件的各个部分,也可以推迟到程序后面再处理。
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
方法readlines()从文件中读取每一行,并将其存储在一个列表中。
5.使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
执行结果为:
在变量pi_string存储的字符串中,包含原来位于每行左边的空格,为删除这些空格,可使用strip()而不是rstrip():
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
执行结果为:
注意:读取文本文件时,python将其中的所有文本都解读为字符串。如果读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,或使用函数float()将其转换为浮点数。
6.包含一百万位的大型文件
前面我们分析的都是一个只有三行的文本文件,但这些代码示例也可以处理大的多的文件。如果我们有一个文本文件,其中包含精确到小数点后1000000位而不是30位的圆周率值,也可创建一个包含所有这些数字的字符串。为此,我们无需对前面的程序做任何修改,只需将这个文件传递给它即可。在这里,我们只打印到小数点后50位。
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[:52] + "...")
print(len(pi_string))
7.圆周率值中包含你的生日吗
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
1.写入空文件
要将文本写入文件,在调用open()时需要提供另一个实参,告诉python我们要写入打开的文件。
write_message.py
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming")
在这个示例中,调用open()时提供了两个实参。第一个实参也是要打开的文件的名称,第二个实参(‘w’)告诉python,我们要以写入文件模式打开这个文件。打开文件时,可指定读取模式(‘r’),写入模式(‘w’),附件模式(‘a’)或让你能够读取和写入文件模式(‘r+’)。如果省略了模式实参,python将以默认的只读模式打开文件。
如果要写入的文件不存在,函数open()将自动创建它。然而,以写入模式(‘w’)打开文件时千万要小心,因为如果指定的文件已经存在返回文件对象前清空该文件。
注意:python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
2.写入多行
函数write()不会在写入文本末尾添加换行符,如果让每个字符串都单独占一行,需要在write()语句中包含换行符:
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
执行结果为:
3.附加到文件
以附加模式打开文件时,python不会在返回文件前清空文件,而我们写入到文件的行都将添加到文件末尾。如果指定的文件不存在,python将为我们创建一个空文件。
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in the browser.\n")
异常是使用try-except代码块处理的。try-except代码块让python执行指定的操作,同时告诉python发生异常时怎么办。使用了try-except代码块时,即便出现异常,程序也将继续运行:显示我们编写的友好的错误消息,而不是另用户迷惑的traceback。
1.处理ZeroDivisionError异常
将一个数字除以0
print(5/0)
python无法这样做,我们将会看到一个traceback:
2.使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
我们将导致错误的代码行 print(5/0)放在了一个try代码块中。如果try代码块中的代码运行起来没有问题,python将跳过except代码块;如果try代码块中的代码导致了错误,python将查找这样的except代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。
执行结果为:
3.使用异常避免崩溃
print("Give me two numbers, and i'll divide them.")
print("Print 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if first_number == 'q':
break
answer = int(first_number) / int(second_number)
print(answer)
print("Give me two numbers, and i'll divide them.")
print("Print 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if first_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
filename = 'alice.txt'
with open(filename) as file_object:
contents = file_object.read()
filename = 'alice.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
执行结果为:
6.分析文本
title = "Alice in Wonderland"
print(title.split())
执行结果为为:
方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。结果是一个包含字符串中 所有单词的列表,虽然有些单词可能包含标点。
filename = 'alice.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + "has about " + str(num_words) + "words.")
7.使用多个文件
def count_words(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + "words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
程序在发生异常的时候就像什么都没发生一样继续执行。
def count_words(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + "words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
相比前一个程序,这个程序唯一不同的地方是pass语句。现在,出现FileNotFoundError异常时,将执行except代码块中的代码,但什么都不会发生。这种错误发生时,不会出现traceback,也没有任何输出。
执行结果为:
9.决定报告哪些错误
如果用户要知道分析哪些文件,他们可能希望在有文件没有分析时出现一条消息,将其中的原因告诉他们。如果用户只想看到结果,而并不知道要分析哪些文件,可能就无需在某些文件不存在时告诉他们。
1.使用json.dump( )和json.load( )
编写一个存储一组数据的简短程序,再编写一个将这些数字读取到内存中的程序。第一个程序将使用json.dump( )来存储这组数据,而第二个程序将使用json.load( )。
函数json.dump( )接受两个实参:要存储的数据以及可用于存储数据的文件对象。
下面演示如何使用json.dump( )来存储数字列表:
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as file_object:
json.dump(numbers, file_object)
这个程序没有输出,但生成了一个number.json文件,其数据的存储格式与python中一致。
下面演示使用json.load( )将列表读取到内存中:
import json
filename = 'number.json'
with open(filename) as file_object:
numbers = json.load(file_object)
print(numbers)
执行结果为:
2.保存和读取用户生成的数据
import json
filename = 'username.json'
try:
with open(filename) as file_obj:
username = json.load(file_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as file_obj:
json.dump(username, file_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
如果这个程序是首次运行,执行结果为:
否则,执行结果为:
这是程序之前至少运行了一次时的输出。
3.重构
我们经常会遇到这样的情况:代码能够正常的运行,但可以做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构。重构让代码更清晰、更易于理解,更容易扩展。
要重构remember.py,可将其大部分逻辑放到一个或多个函数中。remember.py的重点是问候用户,因此我们将其所有代码都放到一个名为greet_user()的函数中:
import json
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as file_obj:
username = json.load(file_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as file_obj:
json.dump(username, file_obj)
return username
def greet_user():
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()