目录
"""1.处理文件,快速分析大量数据2.错误处理,避免程序崩溃3.异常,管理程序运行的错误4.json模块保存用户数据"""1.处理文件,快速分析大量数据
"""
1.处理文件,快速分析大量数据
2.错误处理,避免程序崩溃
3.异常,管理程序运行的错误
4.json模块保存用户数据
"""
1.处理文件,快速分析大量数据
"""
注意文件路径,可以使用绝对文件路径
with open()妥善打开关闭文件
逐行读取文件
rstrip()忽略每行后空格
"""
filename = 'pi_digits.txt'
with open(filename) as object_file:
for line in object_file:#按行遍历文件
print(line.rstrip())
filename = 'pi_digits.txt'
with open(filename) as object_file:
lines = object_file.readlines()#readlines()读取每行并存在列表lines[]中
for line in lines:
print(line.rstrip())
filename = 'pi_digits.txt'
with open(filename) as object_file:
lines = object_file.readlines()#readlines()读取每行并存在列表lines[]中
pi_string = ''
for line in lines:#遍历存储文件的列表
pi_string+=line.strip()#拼接文件内容
print(pi_string)
print(len(pi_string))
filename = 'programming.txt'
with open(filename,'w') as object_file:#写入方式打开文件
object_file.write('i love programming.\n')
object_file.write('i love dog.\n')
with open(filename,'a') as object_file:#附加方式打开文件,不会清空已打开的文件
object_file.write('i love programming.\n')
object_file.write('i love dog.\n')
2.错误处理,避免程序崩溃
"""
异常,返回自己的信息而不是trace back
"""
print("give me two nubers,and i will divide them.")
print("enter 'q' to quit")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond_number: ")
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError:
print("you can't divide by 0!")
else:
print(answer)
3.异常,管理程序运行的错误
#处理文件找不到的错误FileNotFoundError
#分析文本
filename = 'Alice in Wonderland.txt'#别忘了txt格式
try:
with open(filename) as object_file:
contents = object_file.read()#读取进contents
except FileNotFoundError:
print("can't found the file")
else:
words = contents.split()#根据字符串创建列表,以空格为分隔符,
#返回包含字符串所有单词的列表存在words
num_words = len(words)
print("the file "+filename+"has about "+str(num_words)+"words.")
4.json模块保存用户数据
#json存储数据
#json.load(目标文件) json.dump(变量,目标文件),变量写入目标文件并以json格式保存
import json
filename = 'username.json'
try:
with open(filename) as object_file:
username = json.load(object_file)
except FileNotFoundError:
username = input("what's your name? ")
with open(filename,'w') as object_file:
json.dump(username,object_file)
print("we will remeber your name "+ username)
else:
print("welcome back "+ username)