一忌堂、從文件中讀取數(shù)據(jù):
文本文件可以存儲(chǔ)數(shù)據(jù):天氣數(shù)據(jù)、交通數(shù)據(jù)拴曲、社會(huì)經(jīng)濟(jì)數(shù)據(jù)争舞、文學(xué)作品等。
1澈灼,讀取整個(gè)文件:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
2,文件路徑:
相對路徑:當(dāng)前py存儲(chǔ)路徑下
圖片.png
絕對路徑:隨便什么地方都可以
圖片.png
3竞川,逐行讀取:
for line in file_object:
4叁熔,創(chuàng)建一個(gè)包含文件各行內(nèi)容的列表
filename = 'text_files/pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
5,使用文件的內(nèi)容:
pi_string = ''
for line in lines:
pi_string +=line.rstrip()
6,包含一個(gè)百萬位的大型文件:
print(pi_string[:52] + "...")
7,圓周率值中包含你的生日嗎委乌?
birthday = input("Enter your birthday,in the form mmddyy:")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appears in the first million digits of pi!")
二、寫入文件
1荣回,寫入空文件('r'讀取模式遭贸,'w'寫入模式,'a'附加模式):
python只能講字符串寫入文本文件心软。要將數(shù)值數(shù)據(jù)存儲(chǔ)到文本文件中壕吹,必須先使用str()將其轉(zhuǎn)換為字符串格式。
with open(filename,'w') as file_object:
file_object.write("I love programming.")
2删铃,寫入多行算利,可以使用空格、制表符和空行來設(shè)置輸出的格式泳姐。
三效拭、異常:
1,使用try-except代碼塊胖秒,使用異常避免崩潰
print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number:")
if first_number == 'q':
break
second_number = input("Second number:")
if second_number == 'q':
break
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError as e:
print("You can't divide by 0!")
else:
print(answer)
執(zhí)行的錯(cuò)誤代碼放在try中缎患,except告訴python出錯(cuò)怎么處理,else try代碼成功執(zhí)行后的執(zhí)行順序阎肝。
2挤渔,處理FileNotFoundError錯(cuò)誤:
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry,the file" + filename + " dose not exist."
print(msg)
3,使用多個(gè)文件:
filenames = ['text_files/programming.txt','text_files/pi_digits.txt','text_files/111.txt']
for filename in filenames:
count_words(filename)
4,失敗時(shí)一聲不吭,try except后加pass語句
四风题、存儲(chǔ)數(shù)據(jù)
1判导,使用json.dump()和json.load(),可以以json格式存儲(chǔ)文件沛硅,即時(shí)程序關(guān)閉后也能引用眼刃。
import json
numbers = [2,3,5,7,11,13]
filename = 'text_files/numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
import json
filename = 'text_files/numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)