python學習筆記(六)檔案與異常

2021-09-27 10:28:41 字數 1372 閱讀 2954

1、讀取和寫入文字檔案

#它們的返回值是乙個檔案物件

infile = open("input.txt", "r") #以讀模式開啟檔案,檔案必須已經存在

outfile = open("outpt.txt", "w") #以寫模式開啟檔案,檔案不存在會自動建立,若存在會被清空

infile.close()

outfile.close() #若以寫模式開啟檔案退出時不關閉檔案,有可能有些輸出沒有寫進去

line = infile.readline()    #使用該方法可以讀取一行,返回值是字串形式,並且會將換行符也讀進去,類似這種 :flying\n
#方法一:使用write方法

outfile.write("hello world!\n") #如果希望換行,必須顯示地新增換行符

#方法二:使用print函式,會自動換行,若不想換行,可以新增end=""具名引數

print("hello world!", file = outfile)

print("hello world!", end="", file = outfile)

2、文字輸入與輸出

for line in infile :    #line中賦值檔案中下一行文字的乙個字串

print(line)

3、命令列引數

4、二進位制檔案與隨機訪問

5、異常處理

if amount > balanc :

raise valueerror("amount exceeds balance")

balance = balance - amount

try :

filename = input("enter filename: ")

infile = open(filename, "r")

line = infile.readline()

value = int(line)

except ioerror :

print("error: file not found")

except valueerror as exception: #使用as語法將異常物件儲存在變數exception中,以供後面的程式呼叫

print("error:", str(exception))

with open(filename, "w") as outfile :

output.write("000")

6、處理輸入錯誤

7、統計分析

C 學習筆記(六)檔案處理

本文主要講解如何使用c 程式來建立 更新和處理資料檔案,主要考慮順序儲存和隨機儲存檔案兩種方式。c 將每個檔案看成是位元組序列,每個檔案都以乙個檔案結束符或者是儲存在系統維護 管理的資料結構中的乙個特點位元組數作為結尾,而c 使用流物件 一種特殊的類模板的物件,也即流類模板物件 提供程式和檔案之間的...

Perl學習筆記(六) 檔案(一)

一 檔案描述符 訪問檔案時用來代表檔案的數字。它是系統資源,系統限制開啟的檔案描述符數量。perl中只在某些系統呼叫時才使用它 檔案控制代碼 功能同檔案描述符,但是與檔案描述符不是乙個東西。perl使用檔案控制代碼代表檔案。檔案描述符與檔案控制代碼互相轉化 檔案控制代碼 檔案描述符 fileno f...

Python學習筆記 6 檔案

要開啟的檔案應該儲存在你執行的python程式同乙個資料夾下。這個檔案儲存在你啟動python時所在的那個資料夾。fhand open mbox.txt print fhand 如果檔案成功被開啟,作業系統會返回乙個檔案控制代碼。如果檔案不存在,開啟失敗,輸出追蹤錯誤資訊。文字檔案可視為若干文字行的...