一、從文件中讀取數據
#!/usr/bin/env pythonwith open('pi') as file_object: contents = file_object.read() print(contents) ===================================3.1415926 5212533 23242551、逐行讀取
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: for line in file_object: print(line) ===================================3.1415926 5212533 2324255
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: for line in file_object: print(line.rstrip())==================3.1415926 5212533 2324255
2、創建一個包含文件各行內容的列表
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: lines = file_object.readlines() #readlines()方法是從文件中讀取每一行,并將其存儲在一個列表中for line in lines: print(line.rstrip())==============================3.1415926 5212533 2324255
3、使用文件內容
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: lines = file_object.readlines()pi_string = ''for line in lines: pi_string += line.strip()print(pi_string)print(len(pi_string))========================================3.14159265212533232425523
二、寫入文件
1、寫入空文件
#!/usr/bin/env pythonfilename = 'programming.txt'with open(filename,'w') as file_object: file_object.write("I love programming!")2、寫入多行
#!/usr/bin/env pythonfilename = 'programming.txt'with open(filename,'w') as file_object: file_object.write("I love programming!/n") file_object.write("yes!/n")3、附加到文件
#!/usr/bin/env pythonfilename = 'pi'with open(filename,'a') as file_object: file_object.write("I love programming!/n") file_object.write("yes!/n")三、異常
1、使用try-except代碼塊
#!/usr/bin/env python try: print(5/0)except ZeroDivisionError: print("You cant divide by zero!")這里介紹下異常的有關內容。
Python 異常處理
python提供了兩個非常重要的功能來處理python程序在運行中出現的異常和錯誤。你可以使用該功能來調試python程序。
什么是異常?
異常即是一個事件,該事件會在程序執行過程中發生,影響了程序的正常執行。
一般情況下,在Python無法正常處理程序時就會發生一個異常。
異常是Python對象,表示一個錯誤。
當Python腳本發生異常時我們需要捕獲處理它,否則程序會終止執行。
異常處理
捕捉異常可以使用try/except語句。
try/except語句用來檢測try語句塊中的錯誤,從而讓except語句捕獲異常信息并處理。
新聞熱點
疑難解答