10.1 讀取文件常規方法:
with open('document\\.file.txt') as file_object: #windows中用斜槓(\),linux或UNIX中使用反斜槓(/)
concents = file_object.read()
print(concents.rstrip()) #去掉行尾的空格
注意:路徑分爲絕對路徑和相對路徑,windows系統中使用雙斜槓(\\),書中所說的單斜槓(\)會報如下錯誤:
或者寫成:
file_path = 'C:\\Users\\nees-pub\\document\\file.txt' #這裏用的是絕對路徑,依然要用雙斜槓
with open(file_path) as first_file:
concents = first_file.read()
print(concents.rstrip())
10.1.2 逐行讀取文件:for line in ...
file_path = 'document\\file.txt'
with open(file_path) as first_file:
for line in first_file:
print(line.rstrip())
10.1.3 把各行存儲到列表,一行當做一個元素,在用for ... in ...讀取列表打印顯示
file_path = 'document\\file.txt'
with open(file_path) as first_file:
lines = first_file.readlines()
print(lines)
for line in lines:
print(line.rstrip())
10.2.1 寫入文件
Python只能將字符串寫入文本文件。要將數值數據存儲到文本文件中,必須先使用函數str() 將其轉換爲字符串格式。
file_path = 'document\\file.txt'
with open(file_path,'w') as first_file:
first_file.write("I love you!")
'w'位三種寫入模式中的一種,另外還有
'r':讀取模式:只能讀取文檔,10.1讀取文件的寫法是省略了這個參數,也就是如果這個參數省略,則默認是r
'a':附加模式,不清空文檔,在行末添加寫入
注意:w(寫入模式)是覆蓋寫入,寫入之前會把文件清空
例子:附加模式,file.txt位空文件
file_path = 'document\\file.txt'
with open(file_path,'a') as first_file:
first_file.write("I love you!\n")
with open(file_path) as file_project:
print(file_project.read())
第一次執行:
第二次執行:
第三次執行:
10.3.2 異常處理
try:
代碼塊
except 異常1:
異常1的解決辦法
except 異常2:
異常2的解決辦法
except Exception:
剩餘的其他異常解決辦法
注意:如果想要程序遇見異常依然繼續執行,還保持沉默,就用 pass 代替 異常的解決方法
常見異常:
ZeroDivisionError :被除數不能爲0
ValueErrot :值錯誤,比如輸入值的類型錯誤
FileNotFoundError :未找到文件
10.4 json.dump()和json.load()
json.dump():把數據存儲在json文件裏
json.load():把數據文件加載到內存裏
import json
number = [2,3,5,7,1,13]
filename = 'number.json'
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
with open(filename) as f_c:
concents = json.load(f_c)
print(concents)
10.4.2 保存和讀取用戶生成的數據
import json
# 如果以前存儲了用戶名,就加載它
# 否則,就提示用戶輸入用戶名並存儲它
filename = 'username.json'
try:
with open(filename) as f_read:
username = json.load(f_read)
except FileNotFoundError:
username = input("What's your name?")
with open(filename,'w') as f_write:
json.dump(username,f_write)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
10.4.3 文檔字符串和註釋的區別
文檔字符串可以被程序讀取打印,用 三引號“"” 包括起來
註釋只起到解釋說明的作用,前面是 # 做前綴(單行註釋),或者用 三引號“"” 包括起來,如"""註釋"""(多行註釋)
讀取文檔字符串:
#定義一個帶有文檔字符串的簡單函數
def print__hello():
"""this funtion is to print hello """
print("hello")
#下面我們來調用並輸出文檔字符串
print(print__hello.__doc__)
拓展:編碼聲明註釋
# -*- coding:編碼 -*-
或者
# coding=編碼