读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
注:
with的用法:让文件妥善地打开和关闭。
rstrip()函数:消除空行
使用文件的内容:
with open('test_files/pi_digits.txt') 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()将其转化为浮点数。
生日是否包含在圆周率中
with open('pi_million_digits.txt') as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input("Enter your bithday:")
if birthday in pi_string:
print("your birtday appears.")
else:
print("your birthday don't appear.")
#print(pi_string[:6] + "...")
print(len(pi_string))
文件写入
filename = 'programing.txt'
with open(filename,'a') as file_object:
file_object.write("I also love you.\n")
file_object.write("I also love programing.\n")
注:open函数的几种模式:r:读取模式。w:写入模式 a:附件模式,在原有基础上可以添加其他内容。
写入多行注意用\n:换行符号。
使用多个文件,并且失败时一声不吭。
try, except的用法:如果try代码块中的代码运行没问题,Python跳过except代码块。如果try代码运行错误,python将查找这样的except模块,并运行代码。
try, except,else模块中,try执行失败,运行except, 运行成功,执行else模块。
def count_number(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
words = contents.split()
number_words = len(words)
print("The novel " + filename +" has " + str(number_words) + ".")
filenames = ['alice.txt','sidd.txt','moby_dict.txt','little_women.txt']
for filename in filenames:
count_number(filename)
决定报告哪些错误,由用户需求决定。
存储数据
使用json来存储数据。
import json
def 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_name():
username = input("What's your name?")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
username = stored_username()
if username:
print("welcome back," + username + "!")
else:
username = get_new_name()
print("We will be happy,when you come," + username + "!")
greet_user()
重构
将代码划分为一系列完成具体工作的函数。这样的过程称为重构。
重构让代码更清晰,更易于理解,更容易扩展。