讀取整個文件
文件pi_digits.txt
#文件pi_digits.txt 3.1415926535 8979323846 2643383279
下面的程序打開並讀取整個文件,再將其內容顯示到屏幕中:
with open("pi_digits.txt") as fileobject: contents = fileobject.read() print(contents) #運行結果 3.1415926535 8979323846 2643383279
使用函數open()打開文件,函數open(0接受一個要打開的文件的名稱參數,python在當前執行的文件所在的目錄中查找指定的文件。函數open()返回一個表示文件的對象。然后將這個對象保存在后面使用的變量中,也可以說是文件句柄。關鍵字with在不需要訪問文件后將其關閉。在這個程序中,我們沒有使用close()來關閉文件,也可以這樣做,但是如果程序存在bug,導致close()語句未執行,文件將不會關閉。有了表示pi_digits的文件的對象后,我們就可以使用方法read()來讀取內容了,並將其作為一個長長的字符串存儲在變量contents中。
文件路徑
相對路徑:對於當前目錄的路徑
linux中:
with open('text_files/filename.txt') as file_object:
Windows中:
with open('text_files\filename.txt') as file_object:
絕對路徑:相對於根目錄
linux中:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt' with open(file_path) as file_object:
Windows中:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' with open(file_path) as file_object:
創建一個包含文件各行內容的列表
在讀取文件的時候,常常是逐行讀取;
方法readlines()從文件中讀取每一行,並將其存儲在一個列表中;
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() print(lines) for line in lines: print(line.rstrip()) #運行結果 ['3.1415926535\n', ' 8979323846\n', ' 2643383279\n'] 3.1415926535 8979323846 2643383279
寫入空文件
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.\n")
運行結果:
如果文件存在,則覆蓋寫入,若不存在則創建寫入
I love programming.
附加到文件
filename = 'programming.txt' with open(filename,'a') as file_object: file_object.write("I also love python!\n") file_object.write("I love creating apps\n")
#運行結果
在文件末尾添加
I love programming.
I also love python!
I love creating apps
處理異常
先看一個簡單的異常:print(5/0) #運行結果 Traceback (most recent call last): File "D:/python_cd/《Python編程從入門到實踐》/division.py", line 1, in <module> print(5/0) ZeroDivisionError: division by zero
顯然python無法這樣做,因此你將看到一個traceback,指出的錯誤ZeroDivisionError是一個異常對象,這樣python將停止運行程序,下面我們將告訴python發生了這樣錯的時候,該怎么做,而不是終止程序返回報錯。
try: print(5/0) except: print("You can't divide by zero!") #運行結果 You can't divide by zero!
在這個示例中, try代碼塊中的代碼引發了ZeroDivisionError異常,因此Python指出了該如何解決問題的except代碼塊,並運行其中的代碼。這樣,用戶看到的是一條友好的錯誤消息,而不是traceback。
else代碼塊
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: ") try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer) #運行結果 Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 12 Second number: 6 2.0 First number: 12 Second number: 0 You can't divide by 0!
try-except-else代碼塊的工作原理大致如下: Python嘗試執行try代碼塊中的代碼;只有可能引發異常的代碼才需要放在try語句中。有時候,有一些僅在try代碼塊成功執行時才需要運行的代碼;這些代碼應放在else代碼塊中。 except代碼塊告訴Python,如果它嘗試運行try代碼塊中的代碼時引發了指定的異常,該怎么辦。 python中有一個pass語句,可在代碼塊中使用它來讓python都不要做,比如在except語句下只加pass,表示報錯是沒有任何返回。
JSON模塊
模塊json讓你能夠將簡單的Python數據結構轉儲到文件中,並在程序再次運行時加載該文件中的數據。你還可以使用json在Python程序之間分享數據。更重要的是,JSON數據格式並非Python專用的,這讓你能夠將以JSON格式存儲的數據與使用其他編程語言的人分享。這是一種輕便格式,很有用,也易於學習。
import json info={'name':'Tom', 'age':'12', 'job':'work',} f=open('file1.txt','w') f.write(json.dumps(info)) f.close()
json.loads
import json f=open('file1.txt','r') data=json.loads(f.read()) f.close() print(data) print(data['name'])