Python——文件和異常

從文件中讀取數據

  • 使用文本文件中的信息,首先需要將信息讀取到內存中。可以選擇一次性讀取文件的全部內容,也可以選擇逐步讀取

讀取整個文件 read()

with open('pi.txt') as read_file:
    contents = read_file.read()
    print(contents)
  • open()打開文件接收一個參數:要打開的文件的名稱,open返回一個表示文件的對象

  • with表示在不需要訪問文件后將其關閉。而無需調用close.但是調用close會有問題,如果程序存在bug導致close()沒有執行。那么文件將不會關閉

  • read()讀取文件的全部內容,read()在到達文件末尾時會返回一個空的字符串。如果要不顯示這個空字符串使用rstrip()

  • 也可以設置最大的讀入字符數限制read()函數一次返回的大小。

poem = ''
chunk = 10
with open('read_chunk.log', 'rt') as file:
    while True:
        fragment = file.read(chunk)
        if not fragment:
            break
        poem += fragment
print('finish')
print(len(poem))

逐行讀取

  • readlines()調用時每次讀取一行,并返回單行字符串列表
with open('pi.txt') as read_file:
    for line in read_file:
        print(line.rstrip())

創建包含文件各行內容的列表

  • 使用關鍵字with,open()返回的文件對象只在with代碼塊內可用。如果要在with代碼塊外訪問文件的內容,可在with代碼塊內將文件的各行存儲在一個列表中
with open('pi.txt') as file_reader:
    lines = file_reader.readlines()
for line in lines:
    print(line.rstrip())

readlines從文件中讀取每一行并將讀取到的數據存儲在一個列表中。

寫入文件

寫入空文件

  • 要將文本寫入文件,需要在調用open()時需要提供一個實參。告訴Python要寫入打開的文件
filename = 'piwrite.txt'
with open(filename,'w') as file_write:
    file_write.write('123456')
  • open傳入的實參中‘w’是告訴python以寫入模式打開文件。
  • r 讀取模式
  • w 寫入模式
  • a 附加模式
  • r+ 讀取和寫入模式
  • x 表示在文件不存在的情況下新創建并寫文件
  • t(或者省略)代表文本類型
  • b 代表二進制文件
  • 如果要寫入的文件不存在,函數open()將自動創建。如果以寫入'w'模式打開文件時指定的文件已經存在,python將在返回文件對象前清空該文件
  • Python只能將字符串寫入文本文件。要將數值等數據存儲到文本文件中,必須先使用函數str()將其轉換為字符串格式

寫入多行文件

  • write()不會再寫入的文本末尾添加換行符。需要在寫入的文本中指定‘\n’換行

使用write()寫二進制文件

如果文件模式字符串中包含'b',那么文件會以二進制模式打開,在這種情況下,讀寫的是字節而不是字符串

使用seek() 改變位置

無論是讀或者寫文件,Python都會跟蹤文件匯總的位置,函數tell()返回距離文件開始處的字節偏移量。函數seek()允許跳轉到文件其他字節偏移量的位置。
seek跳轉的是字節的偏移量,所以打開文件方式需要使用二進制模式b

  • seek(offset,origin)
    • 如果origin等于0,從開頭偏移offset個字節
    • 如果origin等于1,從當前位置處偏移offset個字節
    • 如果origin等于2,距離最后結尾處偏移offset個字節
  • 系統常量定義
import os
os.SEEK_SET # 從文件開頭偏移offset個字節
>>> 0
os.SEEK_CUR # 從當前位置處偏移offset個字節
>>> 1
os.SEEK_END # 從距離最后結尾處偏移offset個字節
>>> 2
import os
with open('read_chunk.log', 'rb') as file:
    print(file.tell())  # 返回當前距離文件開始的偏移量
    print(file.seek(1, os.SEEK_END))

結構化的文本文件

XML

在Python中解析XML最簡單的方法是使用ElementTree

  • tag是標簽字符串
  • attrib 是它屬性的一個字典
import xml.etree.ElementTree as et
tree = et.ElementTree(file='test_xml.xml')
root_tag = tree.getroot()
print(root_tag.tag)
for child in root_tag:
    print(child.tag)
note
to
from
heading
body

json

Python使用json模塊來進行json解析

  • 使用json的dumps將menu編碼城JSON字符串
import json
json_str = ''
with open('json_file', 'rt') as file:
    json_str = file.read()
json = json.dumps(json_str)
print(json_str)
>>> {"breakfast": {  "hours": "7- 11",  "items": {  "breakfast burritos": "$6. 00",  "pancakes": "$4. 00"  }  },  "lunch" : {  "hours": "11- 3",  "items": {  "hamburger": "$5. 00"  }  },  "dinner": {  "hours": "3- 10",  "items": {  "spaghetti": "$8. 00"  }}}
  • 使用loads把json字符串解析成Python的數據結構
import json
json_str = ''
with open('json_file', 'rt') as file:
    json_str = file.read()
json_a = json.dumps(json_str)
# 將json字符串解析成Python數據結構
python_data = json.loads(json_a)
test = eval(python_data)
print(test)

異常

Python使用被稱為異常的特殊對象來管理程序執行期間發生的錯誤。當Python發生錯誤時,都會創建一個異常對象。如果處理了異常,程序將繼續運行。如果沒有對異常進行處理,程序將停止。

  • 異常是使用try-except代碼塊處理的。try-except讓Python執行指定的操作。

處理ZeroDivisionError異常

try:
    print(5/0)
except ZeroDivisionError:
    print('error happend')
  • try-except捕獲異常后程序可以繼續執行
try:
    print(5/0)
except ZeroDivisionError:
    print('error happend')
# else:
print('program continue') #這行代碼會被執行

異常else代碼塊

try-except-else:Python嘗試執行try代碼塊中的代碼;如果try代碼塊中的代碼成功執行,則會后續執行else代碼塊中的代碼。

try:
    print(5/0)
except ZeroDivisionError:
    print('error happend')
else:
    print('program continue')

finally代碼塊

異常處理中的finally代碼塊是最后執行的,無論是否有異常,finally代碼塊肯定會執行

t = 0
try:
    i = 5
    t = 5 / 0
except Exception as e:
    print(e)
    t = 3
finally:
    print(t)

主動觸發異常

使用raise 可以主動拋出異常,raise代表程序會主動觸發一個異常。被捕獲

t = 0
try:
    i = 5
    raise Exception('error')
except Exception as e:
    print(e)
    t = 3
finally:
    print(t)
>>>
error
3

處理FileNotFoundError異常

  • 在使用文件時,要查找的文件可能不存在,我們使用下面的程序
filename = 'pi2.txt'
with open(filename) as file_obj:
    print(file_obj)

當pi2.txt不存在時會引發異常,我們使用異常捕獲這個異常,可以發現程序不會報錯

filename = 'pi2.txt'
try:
    with open(filename) as file_obj:
        print(file_obj)
except FileNotFoundError:
    print('file not found')
print('program continue')

使用pass替代執行語句

  • Python中有一個pass語句,可在代碼塊中使用,pass語句充當了占位符,表示什么都不做
filename = 'pi2.txt'
try:
    with open(filename) as file_obj:
        contents = file_obj.read()
except FileNotFoundError:
    pass

使用json模塊來存儲數據

模塊json能夠將簡單的Python數據結構轉儲到文件中,并在程序再次運行時加載該文件中的數據,json在Python之間可以分享數據。

使用json.dump()和json.load()

  • 函數json.dump()接受兩個實參:
    1、要存儲的數據
    2、存儲數據的文件對象
import json

numbers = [1, 2, 3, 4, 5, 6, 7]
filename = 'pi2.txt'
try:
    with open(filename, 'w') as file_obj:
        json.dump(numbers, file_obj)
except FileNotFoundError:
    pass
else:
    print('program success')

json.load()讀取數據

  • json.load()傳入要讀取的文件對象
import json

filename = 'pi2.txt'

try:
    with open(filename, 'r') as read_file:
        numbers = json.load(read_file)
except FileNotFoundError:
    pass
else:
    print(numbers)
  • eg: 記住用戶名稱
import json

filename = 'user.json'
# 讀取文件捕捉異常
try:
    with open(filename) as user_file:
        username = json.load(user_file)
except FileNotFoundError:
    username = input('plz input your name')
    with open(filename, 'w') as user_write_file:
        json.dump(username, user_write_file)
    print("i remeber you when you come back i'll call you")
else:
    print('hello' + username)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容