一、从文件中读取数据
1.使用方法read()读取整个文件
(1)使用open()函数打开文件,调用open()函数时,需要向其传递一个参数,打开文件的名称、Python会在当前执行的文件所在的目录中查找指定的文献。注意,如果需要打开的文件与当前运行的程序文件不在同一目录时,则需要提供文件的路径(又分为相对文件路径和绝对文件路径),让Python到系统的特定位置去查找。
(2)使用关键字with,让Python在合适的时机将所访问文件关闭
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as f:
contents = f.read()
print(contents)
2.使用for循环逐行读取文件
filename = 'pi_digits.txt'
with open(filename) as f:
for line in f:
print(line.rstrip())
3.使用方法readlines()创建一个包含文件各行内容的列表:使用关键字with时,open()函数返回的内容只在with代码块内可用。如果要在with代码块外,访问文件的内容,可使用方法readlines()从文件中读取每一行,并将其储存在一个列表中
filename = 'pi_digits.txt'
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip())
注意:在读取文件时,Python将其中所有的文本都解读为字符串。如果读取的是数,并要将其作为数值使用,就比需使用函数int()将其转换为整数或使用函数float()将其转换为浮点数
二、利用方法write()写入文件
1.写入空文件:通过向open()指定另一个实参‘w’的方式,可以写入文件;当写入的文件不存在时,函数open()会自动创建它。
(1)类似的模式实参有读取模式(‘r’)、写入模式(‘w’),附加模式(‘a’)或者读写模式(r+),如果省略模式实参,Python将以默认的只读模式打开文件。
(2)函数write()不会在写入的文本末尾添加换行符,因此如果想要写入多行时,应该自行在字符串末尾加入换行符\n
2.附加到文件:以写入模式打开文件时,Python会自动清空文件对象内的内容。因此如果想要给文件添加内容时,而不是覆盖掉原有内容时,可以以附加模式(‘a’)打开文件
filename = 'programming.txt'
with open(filename, 'a') as f:
f.write("I love Python!\n")
f.write("What about you, my friend?\n")
三、异常
1.异常:异常是Python用来管理程序执行期间发生错误的特殊对象。异常使用try-except代码块以及else代码块进行处理:try代码块中只包含可能引起错误的代码,except代码块告诉Python如果发生了该种可能的异常应该如何进行处理(也可输入pass,来静默失败),else代码块中放置try代码块成功执行后需要运行的代码
2.处理ZeroDivisionError异常的实例
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
While True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
3.处理FileNotFoundError异常
4.分析文本:方法split()可以以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储在一个列表中
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the filec{filename} does not exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
5.结合for循环可以同时处理多个文本
def count_numbers():
"""计算一个文本中包含多少个单词"""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
words = contents . split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
filenames = ['alice.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_numbers(filename)
四、使用Json模块存储数据
1、使用json.dump()和json.load():
(1)json.dump()函数可存储数据,其接受两个实参:一是要存储的数据、二是可用于存储数据的文件对象
(2)json.load()函数可加载数据
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
with open(filename) as f:
numbers = json.load(f)
print(numbers)
2.保存和读取用户生成的数据
import json
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("Tell me your name: "
with open(filename, 'w') as f:
json.dump(username, f)
print("We will remember it, next time")
else:
print(f"Welcome back, {username}")
3.重构:在代码可以正常运行的情况下,通过将其划分为一系列完成具体工作的函数,来加以改进的过程称为重构。重构可让代码更清晰,更易于理解,更容易扩展