一、从文件读取数据
1.1 读取整个文件
pi.digits.txt
3.1415926535
8979323846
2643383279
file_reader.py
with open("pi_digit.txt") as file_0:
contents=file_0.read()
print(contents)
3.1415926535
8979323846
2643383279
with open("pi_digit.txt") as file_0:
contents=file_0.read()
print(contents.rstrip())#可删除字符串末尾的空白
1.2 文件路径
有时文件会存储在绝对路径中,就不能通过相对路径的方式查找。文件绝对路径中使用反斜杠(/)!!!
'''注意文件绝对路径中使用反斜杠!!!'''
with open("D:/Python/begin_learn/Chapter10/pi_digit.txt") as file_0:
contents=file_0.read()
print(contents.rstrip())
'''可用变量保存文件绝对路径'''
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
contents=file_0.read()
print(contents.rstrip())
1.3 逐条读取
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
for line in file_0:
print(line)
3.1415926535
8979323846
2643383279
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
for line in file_0:
'''可用于删除空白行'''
print(line.rstrip())
1.4 创建一个包含文件各行内容的列表
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
'''从文件中读取每一行,并存储到列表中'''
lines=file_0.readlines()
for line in lines:
print(line.strip())
print(lines)
3.1415926535
8979323846
2643383279
['3.1415926535\n', ' 8979323846\n', ' 2643383279']
1.5 使用文件的内容
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
lines=file_0.readlines()
pi_string=""
for line in lines:
pi_string+=line.rstrip()
print(pi_string)
print(len(pi_string))
3.1415926535 8979323846 2643383279
36
其中,将line.rstrip()改为line.strip()可删除所有的空格。
filename="D:/Python/begin_learn/Chapter10/pi_digit.txt"
with open(filename) as file_0:
lines=file_0.readlines()
pi_string=""
for line in lines:
pi_string+=line.strip()
'''删除所有的空格'''
print(pi_string)
print(len(pi_string))
3.141592653589793238462643383279
32
1.6 包含一百万位的大型文件
在这里,只打印小数点后50位。
filename="D:/Python/begin_learn/Chapter10/pi_million_digits.txt"
with open(filename) as file_0:
lines=file_0.readlines()
pi_string=""
for line in lines:
pi_string+=line.strip()
'''删除所有的空格'''
print(pi_string[:52]+"...")
print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...
4153968
1.7 圆周率中包含你的生日吗?
pi_check_num.py
filename="D:/Python/begin_learn/Chapter10/pi_last_1000000_digits.txt"
with open(filename) as file_0:
lines=file_0.readlines()
pi_string=""
for line in lines:
pi_string+=line.strip()
birthday=input("Enter your birthday mmddyy:")
if birthday in pi_string:
print("Your bithday in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
Enter your birthday mmddyy:121404
Your bithday in the first million digits of pi!
二、写入文件
2.1 写入空文件
programming.py
filename="programming.txt"
'''其中w表示write'''
with open(filename,"w") as file_1:
file_1.write("I love programming.")
programming.txt
I love programming.
2.2 写入多行
filename="programming.txt"
with open(filename,"w") as file_1:
file_1.write("I love programming.\n")
file_1.write("I love creating new games.\n")
filename="programming.txt"
with open(filename,"w") as file_1:
file_1.write("I love programming.\n")
file_1.write("I love creating new games.\n")
2.3 附加到文件
add_programming.py
filename="programming.txt"
'''其中a表示给文件增加内容'''
with open(filename,"a") as file_1:
file_1.write("I love finding meaning in large datasets.\n")
file_1.write("I love creating apps that can run in a browser.\n")
I love programming.
I love creating new games.
I love finding meaning in large datasets.
I love creating apps that can run in a browser.
三、异常
3.1 处理ZeroDivisionError异常
print(5/0)
3.2 使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
You can't divide by zero!
3.3 使用异常避免崩溃
下面的代码如果不注意输入,例如输入5和0,就会报错。
print("Give me two numbers, and I'll divide them.")
print("Enter a 'q' to quit.")
while True:
first_num=input("\nFirst number:")
if first_num=='q':
break
second_num=input("\nSecond number:")
if second_num=='q':
break
answer=int(first_num)/int(second_num)
print(answer)
3.4 else代码块
print("Give me two numbers, and I'll divide them.")
print("Enter a 'q' to quit.")
while True:
first_num=input("\nFirst number:")
if first_num=='q':
break
second_num=input("\nSecond number:")
if second_num=='q':
'''使用代码块来对可能发生错误的代码进行提前预判'''
try:
answer=int(first_num)/int(second_num)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
Enter a 'q' to quit.
First number:1
Second number:0
You can't divide by 0!
First number:1
Second number:1
1.0
First number:q
3.5 处理FileNotFoundError异常
filename="alice.txt"
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
msg="Sorry,the file "+filename+"does not exist."
print(msg)
Sorry,the file alice.txtdoes not exist.
3.6 分析文本
alice.txt
Alice in Wonderland
spilt_words.py
filename="D:/Python/begin_lear/Chapter10/Ch10_3/alice.txt"
try:
with open(filename) as f_obj:
contents=f_obj.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.")
The file alice.txt has about 3 words.
3.7 使用多个文件
count_words.py
def count_words(filename):
try:
with open(filename) as f_obj:
contents=f_obj.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","little_women.txt"]
for filename in filenames:
count_words(filename)
The file alice.txt has about 3 words.
The file little_women.txt has about 7 words.
3.8 失败时一声不吭
except FileNotFoundError:
pass
四、存储数据
4.1 使用json.dump()和json.load()
其中json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象;json.load()加载存储在number_json中的信息。
number_writer.py
#使用json.dump()存储
import json #导入模块json
numbers=[2,3,5,7,11,13]
#文件名称
filename="numbers.json"
#将数据写入
with open(filename,"w") as file_obj:
json.dump(numbers,file_obj)
number_reader.py
import json #导入模块json
filename="numbers.json"
with open(filename) as file_obj:
numbers=json.load(file_obj)
print(numbers)
4.2 保存和读取用户生成的数据
remember_me.py
import json
user_name=input("What's your name?")
filename="username.json"
with open(filename,"w") as file_obj:
json.dump(user_name,file_obj)
print("We will remember you when you come back, "+user_name+" !")
We will remember you when you come back, Ann !
greet_me.py
import json
filename="username.json"
with open(filename) as file_obj:
user_name=json.load(file_obj)
print("Welcome back, "+user_name+"!")
Welcome back, Ann !
4.3 重构
remember_me.py
import json
def greet_user():
#如果存储过用户名,就加载它;反之,提示输入用户名
filename="username.json"
try:
with open(filename) as file_obj:
user_name=json.load(file_obj)
except FileNotFoundError:
user_name=input("What's your name?")
with open(filename,"w") as file_obj:
json.dump(user_name,file_obj)
print("We will remember you when you come back, "+user_name+" !")
else:
print("Welcome back, "+user_name+"!")
greet_user()
greet_user.py
import json
#存储过用户,就获取它
def get_stored_username():
filename="username.json"
try:
with open(filename) as file_obj:
user_name=json.load(file_obj)
except FileNotFoundError:
return None
else:
return user_name
def get_new_username():
username=input("What's 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:
username=input("What's your name?")
filename="username.json"
with open(filename,"w") as file_obj:
json.dump(username,file_obj)
print("We will remember you when you come back, "+username+" !")
greet_user()