1、讀取文件json
一、讀取整個文件ide
file_name = 'cat.txt'spa
with open(file_name) as file_object:ip
contents = file_object.read()input
print(contents) string
二、逐行讀取,可以使用for循環it
file_name = 'cat.txt'for循環
with open(file_name) as file_object:import
for line in file_object:重構
print(line.rstrip())
三、建立一個包含文件各行內容的列表
file_name = 'cat.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
四、使用文件的內容
file_name ='pi.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ' '
for line in lines:
pi_string += line
print(pi_string)
2、寫入文件
一、‘w’寫入
with open(filename,'w') as file_object:
file_object.write(I want to hide")
注:寫入多行時後面須要加換行符。
二、‘a'附加
with open(filename,'a') as file_object:
file_object.write('I want to sleep')
3、異常
try-except-else
else在try代碼塊中執行成功時運行else代碼塊。
4、存儲數據
一、json.dump() 接受兩個實參,要存儲的數據,以及要存儲數據的文件類型
json.load()接受一個實參,文件類型
二、如何用json.dump()來存儲列表
import json
numbers = [1,2,3,4,5,6]
filename = number.josn
with open(filename,'w') as file_object:
josn.dump(numbers,file_object)
三、保存和讀取用戶生成的數據
import json
file_name = 'number.json'
try:
with open(file_name) as file_object:
fav_number = json.load(file_object)
except:
number = input("請輸入你喜歡的數字:")
with open(file_name,'w') as file_object:
fav_number = json.dump(number,file_object)
else:
print("您最喜歡的數字是:%s" % fav_number)
四、重構
import json
file_name = 'username.json'
def got_name():
"""獲取用戶名稱"""
try:
with open(file_name) as file_object:
user_name = json.load(file_object)
except:
return None
else:
return user_name
def new_name():
"""提醒用戶輸入名字"""
user_name = input("請輸入您的名字:")
with open(file_name,'w') as file_object:
put_name = json.dump(user_name,file_object)
return user_name
def greet():
"""向用戶發出問候"""
username = got_name()
if username:
ask = input("用戶名是%s嗎?"%username)
if ask == 'y':
print("歡迎回來%s"%username)
else:
user_name =new_name()
print("下次我會記得你哦!%s"%user_name)
else:
user_name = new_name()
print("下次我會記得你哦!%s" % user_name)
greet()