文件的读写:
代码语言:javascript复制with open(filename, 'a', encoding='utf-8') as file:
with :后面不必写close文件 第二个参数:‘a’ 追加;‘w’ 写;‘r’ 读 encoding = ‘utf-8’ 编码格式,中文的话一般写上
代码语言:javascript复制enter = 'y'
while enter == 'y':
name = input("请输入你的名字:")
filename = "guest_record.txt"
if name != "":
with open(filename, 'a', encoding='utf-8') as file:
file.write(name 'n')
print("hello, ", name, " !")
conti = 'y'
while conti == 'y':
reason = input("你为什么喜欢python?")
with open(filename, 'a', encoding='utf-8') as file:
file.write(reason 'n')
conti = input("继续输入原因吗?y/n ")
enter = input("继续访问吗?y/n ")
file.readlines()
文件按行读取存在列表内
file.read()
整体读取
filename = 'pi_digits.txt'
with open(filename) as pi_file: #with帮助我们适时关闭文件
lines = pi_file.readlines() #把文件按行存储
pi_str = ''
for line in lines:
pi_str = line.strip() #strip()行左右的空删除
print(pi_str[:7] "...")
print(len(pi_str))
birthday = input("输入你的生日:yyyymmdd ")
if birthday in pi_str:
print("你的生日出现在pi中。")
else:
print("你的生日不在pi中。")
代码语言:javascript复制filename = 'learning_python.txt'
with open(filename) as file:
'''方法1:整个文件一次读取'''
# print(file.read())
'''方法2:分行读取'''
# for line in file.readlines():
# print(line.strip())
'''方法3'''
line1 = file.readlines()
for l in line1:
print(l.replace("Python", "C ").strip())
try;except;else
(try代码块出错后,执行except部分,未出错,执行else)
错误处理可以使程序不至于崩溃,还可以继续运行
print("input 2 numbers to divide, enter 'q' to quit.")
while True:
first = input("nfirst num: ")
if first == 'q':
break
second = input("nsecond num: ")
try:
answer = int(first) / int(second)
except ZeroDivisionError:
print("divide zero!!!")
else:
print(answer)
break
filename = 'learning_python.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " filename " does not exist."
print(msg)
# pass #一言不发,跳过
else:
words = contents.split()
print("the title ", filename, " has ", str(len(words)), " words.")
while True:
print("input 2 nums : ")
try:
a = int(input('first num: '))
except ValueError:
print("请输入数字!")
continue
try:
b = int(input('second num: '))
except ValueError:
print("请输入数字!")
continue
print("sum of two nums is ", a b)
json文件存储
代码语言:javascript复制json.dump(object, file)
json.load(file)
代码语言:javascript复制import json
numbers = [2, 3, 5, 7, 11, 13]
filename = "numbers.json"
with open(filename,'w') as file:
json.dump(numbers,file)
with open(filename) as file:
numbers = json.load(file)
print(numbers)
def get_stored_username():
filename = "username.json"
try:
with open(filename) as file:
username = json.load(file)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username = input("What is your name? ")
filename = "username.json"
with open(filename, 'a') as file:
json.dump(username, file)
return username
def greet_user():
username = get_stored_username()
if username:
print("Welcome back, ", username, " !")
else:
get_new_username()
print("We'll remember you when you come back, ", username, " !")
greet_user()
代码语言:javascript复制import json
def get_num():
try:
global favor_num
favor_num = int(input("输入你喜欢的数字:"))
except ValueError:
print("你输入的不是数字,请重新输入!")
get_num()
return favor_num
def store_num(num):
filename = "user_favor_num.json"
with open(filename, 'a') as file:
json.dump(num, file)
def getAndStore():
store_num(get_num())
def print_num():
filename = "user_favor_num.json"
try:
with open(filename) as file:
num = json.load(file)
except FileNotFoundError:
getAndStore()
else:
print("i know your favorite number! it is ", num)
print_num()