本文使用的书籍是《Python编程:从入门到实践》
本文使用的是Python3.6
一、从文件中读取数据
这一节主要讲的是如何读取文件,无非就是几个方法而已。
- 读取整个文件
首先创建一个文件
3.1415926335
8979323846
2643383279
保存在pi_digits.txt
接下来我们用程序打开并读取这个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
注意,程序和pi_digits.txt要放在同一目录下。
根据程序输出的结果,发现输出末尾多了一个空行,我们要使用rstrip()来删除多出来的空行。
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
-
文件路径
当你需要读取放在文件夹的文件的时候,就要把路径放在open里
windows记得是用
Linux和OS X使用/
with open(‘路径\文件名’) as file_object -
逐行读取
with open('pi_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())
- 创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
- 使用文件的内容
filename = 'pi_30_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))
这样,我们就得到了文件中的数据了。
- 包含一百万位的大型文件
filename = 'pi_million_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))
这个跟上面的操作差不多,没有什么不同,就是所用数据更大而已。
- 圆周率值中包含你的生日吗
filename = 'pi_million_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 digit of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")")
动手试一试:
# 10-1
filename = 'learning_python.txt'
with open(filename) as file_object:
print('第一种:')
print(file_object.read().rstrip())
with open(filename) as file_object:
print('第二种:')
for line in file_object:
print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
print("第三种:")
for line in lines:
print(line.rstrip())
# learning_python.txt
In python you can print.
In python you can input.
In python you can make a list.
# 10-2
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.replace('python', 'Java').rstrip())
二、写入文件
这一节主要讲的是写文件,跟读文件差不多233。
- 写入空文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write('I love programming.')
注意:现在open()里除了文件名,还有另一个参数’w’,这个参数代表的是写入模式。
除此之外,还有其他模式:
参数 | 模式 |
---|---|
w | 写入模式 |
r | 读取模式 |
a | 附加模式 |
r+ | 读取和写入模式 |
【重点注意!!!注意!!注意了!】
如果你使用’w’写入模式的时候,在打开文件时千万要注意,如果文件夹没有文件的话,程序会自动创建文件;如果有文件的话,程序会删除原来就有的文件,在创建一个文件,也就是覆盖原文件。
- 多行写入
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write('I love programming.\n')
file_object.write('I love creating new game.\n')
记得每一句话在需要换行的地方都要加’\n’,不然语句会挤在一起。
- 附加到文件
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 a brower.\n')
这里使用’a’来表示进行附加模式,将语句写到文件的后面,而不是覆盖文件。
动手试一试:
# 10-3
filename = 'guest.txt'
while True:
name = input('请输入你的名字:')
if name == 'quit':
break
with open(filename, 'a') as file_object:
file_object.write(name)
# 10-4
import time
filename = 'guest_book.txt'
while True:
name = input('请输入你的名字:')
if name == 'quit':
break;
print(name + ', 欢迎你登录!')
with open(filename, 'a') as file_object:
file_object.write(name + '于' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + '进行登录' + '.\n')
三、异常
python使用异常的特殊对象来管理程序执行期间发生的错误。
如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
- 处理ZeroDivisionError异常
下面来看一种导致Python引发异常的简单错误。
print(5/0)
OK,这个程序运行时肯定会报错,众所周知,数字是不能除以0的,233。
下面我们来看一下如何处理。
- 使用try-except代码块
try:
pritn(5/0)
except:
print("You can't divide by zero!")
这里我们可以看到try-except代码块的使用方法,在try中写入可能或必定233会出错的代码,当try中代码出错时,程序将会执行except中的语句。
- 使用异常避免崩溃
发生错误是,如果程序还有工作没有完成,妥善地处理错误就尤其重要。
当你写完一个程序的时候,总有一些人为因素导致的错误,就比如上面的ZeroDivisionError,虽然你知道不能除零,但总有人会试试233。
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;
answer = int(first_number)/int(second_number)
print(answer)
类似这样,当然你以后可能会写更复杂的程序,更应该要写好异常,有助于发现错误。
- else代码块
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:
print('You can't divide by 0!')
else:
print(answer)
在上面代码中,如果没有发生错误,程序执行完try代码块后,会执行else代码块,不执行except代码块;如果发生错误,首先在try代码块中报错的语句是不能运行的,然后程序会运行except语句,不执行else代码块。
- 处理FileNotFoundError异常
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does noe exist."
print(msg)
- 分析文本
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does noe exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
- 使用多个文件
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does noe exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'alice.txt'
count_words(filename)
- 失败时一声不吭
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'alice.txt'
count_words(filename)
- 决定报告那些错误
……
动手试一试:
# 10-6
while True:
first_number = input('\nFirst number: ')
if first_number == 'quit':
break;
second_number = input('Second number: ')
if second_number == 'quit':
break;
try:
result = int(first_number) + int(second_number)
except ValueError:
print('请输入数字!')
else:
print(result)
# 10-7
while True:
first_number = input('\nFirst number: ')
if first_number == 'quit':
break;
second_number = input('Second number: ')
if second_number == 'quit':
break;
try:
result = int(first_number) + int(second_number)
except ValueError:
print('请输入数字!')
else:
print(result)
# 10-8
def read_file(filename):
try:
with open(filename) as f_obj:
lines = f_obj.readlines();
except FileNotFoundError:
print('File not found')
else:
for line in lines:
print(line.rstrip())
cats = 'cats.txt'
dogs = 'dogs.txt'
read_file(cats)
rad_file(dogs)
# 10-9
def read_file(filename):
try:
with open(filename) as f_obj:
lines = f_obj.readlines();
except FileNotFoundError:
pass
else:
for line in lines:
print(line.rstrip())
cats = 'cats.txt'
dogs = 'dogs.txt'
read_file(cats)
rad_file(dogs)
# 10-10
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
print(contents.lower().count('the'))
filenames = ['Slavery in History.txt', 'John Lackland.txt']
for filename in filenames:
count_words(filename)
四、存储数据
这一节中使用学习使用json进行存储数据。
- 使用json.dump()和json.load()
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
使用json.dump()存储数据
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
使用json.load()读取数据
- 保存和读取用户生成的数据
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name?")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("we'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
这段代码是前面的整和,对各块知识的应用。
- 重构
这一小节里要学习使方法的任务简单化……
首先,先把上面的代码变成一个函数:
import json
def greet_user():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name?")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("we'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
greet_user()
接下来,我们把读取用户名的方法分离,重构greet_user()方法
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
"""问候用户,并指出名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = input("What is your name?")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("we'll remember you when you come back, " + username + "!")
greet_user()
最后,再把写入数据拆出来,重构greet_user()
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_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 f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""问候用户,并指出名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("we'll remember you when you come back, " + username + "!")
greet_user()
动手试一试:
# 10-11
# 写入文件
import json
filename = 'favorite_number.json'
favorite_number = int(input('input your favorite number: '))
with open(filename, 'w') as f_obj:
json.dump(favorite_number, f_obj)
# 读取文件
import json
filename = 'favorite_number.json'
with open(filename) as f_obj:
favorite_number = json.load(f_obj)
print("I know your favorite number! It's " + str(favorite_number))
# 10-12
import json
filename = 'favorite_number.json'
try:
with open(filename) as f_obj:
favorite_number = json.load(f_obj)
except:
favorite_number = int(input('input your favorite number: '))
with open(filename, 'w') as f_obj:
json.dump(favorite_number, f_obj)
else:
print("I know your favorite number! It's " + str(favorite_number))
# 10-13
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_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 f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""问候用户,并指出名字"""
username = get_stored_username()
if username:
usernameB = input(username + ", Is it your name?(Y/N)")
if usernameB == 'N':
username = get_new_username()
elif usernameB == 'Y':
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("we'll remember you when you come back, " + username + "!")
greet_user()
OK,那么这章就结束了!