一、从文件中读取数据:
文本文件可以存储数据:天气数据、交通数据、社会经济数据、文学作品等。
1,读取整个文件:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
2,文件路径:
相对路径:当前py存储路径下
绝对路径:随便什么地方都可以
3,逐行读取:
for line in file_object:
4,创建一个包含文件各行内容的列表
filename = 'text_files/pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
5,使用文件的内容:
pi_string = ''
for line in lines:
pi_string +=line.rstrip()
6,包含一个百万位的大型文件:
print(pi_string[:52] + "...")
7,圆周率值中包含你的生日吗?
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 appears in the first million digits of pi!")
二、写入文件
1,写入空文件('r'读取模式,'w'写入模式,'a'附加模式):
python只能讲字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用str()将其转换为字符串格式。
with open(filename,'w') as file_object:
file_object.write("I love programming.")
2,写入多行,可以使用空格、制表符和空行来设置输出的格式。
三、异常:
1,使用try-except代码块,使用异常避免崩溃
print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst 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 as e:
print("You can't divide by 0!")
else:
print(answer)
执行的错误代码放在try中,except告诉python出错怎么处理,else try代码成功执行后的执行顺序。
2,处理FileNotFoundError错误:
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry,the file" + filename + " dose not exist."
print(msg)
3,使用多个文件:
filenames = ['text_files/programming.txt','text_files/pi_digits.txt','text_files/111.txt']
for filename in filenames:
count_words(filename)
4,失败时一声不吭,try except后加pass语句
四、存储数据
1,使用json.dump()和json.load(),可以以json格式存储文件,即时程序关闭后也能引用。
import json
numbers = [2,3,5,7,11,13]
filename = 'text_files/numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
import json
filename = 'text_files/numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)