python从入门到实践-10章文件和异常(括号问题)

#!/user/bin/env python
# -*- coding:utf-8 -*-

# 1.从文件中读取数据
with open('pi_digits.txt') as file_object:
contents = file_object.read()
# print(contents)
# 末尾会多一行空行,read()到文件末尾时会返回一个空字符,rstrip()删除末尾空白
print(contents.rstrip()) # [有点问题]

# 文件打开可以使用绝对路径和文件名

# 可以使用分开的方式
# filename = 'pi_digits.txt'
# open(filename)

# 使用关键字with时,open()返回的文件对象只在with代码块内部可用。可以不用关闭文件close()
# 要with外的代码块使用,将with代码类文各行储存在一个列表中
# readlines()

# 注意:文件读取的时侯,python将所有文本文件都解读为字符串。需要数字必须转化int() float()

# 2.写入文件
# 注意;写入只能是文本文件,存数字需要转化 str()
file_name = 'programming.txt'
with open(file_name,'w') as file_object:
file_object.write("I love programming.\n") # 换行符也是必须的,python不会自动换行
file_object.write("I love programming.")
# 附件到文件:打开方式 a
# r+ w+ a+ 一般不推荐使用

# 3.异常 try except else (else 执行必须是try执行成功)
try:
print(5/0)
except ZeroDivisionError:
print("you can't divide by zero")

# 使用异常处理避免崩溃
# else代码块

# print("Give me tow numbers, I'll divide them.")
# print("Enter 'q' to quit")
# while True:
# frist = input("\nFrist number:")
# if frist == 'q':
# break
# second = input("Second number:")
# try:
# answer = int(frist) / int(second)
# except ZeroDivisionError:
# print("you can't divide by zero")
# else:
# print(answer)
# 处理文件不存在异常也是一样;try 必须放在open的前面,一位一样是由open引起的
# 分析文本使用.split()方法,将字符串拆分为多个字符

# 打开多个文件 候将这些文件名保存到列表中for循环打开
# pass语句 错误分析时什么都不做

# 4.存储数据 json
# json 数据非python专用,可以与其他编程语言共享
# 存:json.dump() 读:json.load()

# import json
# numbers = [2,3,5,6,7,11]
# filename = 'numbers.json'
# with open('number.json','w') as f_obj:
# json.dump(numbers,f_obj) # 注意格式 前面写入的文件 后面是被改写

# 【json.load有点问题】

# import json
# filename = 'number.json'
# filename.strip()
# with open(filename) as flie:
# number = json.load(flie)
# print(number)

# 可以动态的存入文件

 

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 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 bake, " + username + "!")


greet_user()

posted @ 2018-10-30 22:19  alfred_hong  阅读(151)  评论(0编辑  收藏  举报