1. 程式人生 > 實用技巧 >操作檔案1

操作檔案1

with open('readerFile.txt') as file_object:
    contents = file_object.read()
    print(contents)
  file_object.close()

要現在這個你書寫的.py的資料夾裡去新增一個readFile.txt檔案,注意這個資料夾裡不能新增漢字,open(引數1),這個函式是開啟一個引數1的檔案,這個引數1是檔案的名字

open()函式會返回這個檔案的一個物件,可以使用as後加一個名字,例如這個上的file_object就是這個檔案的一個物件。當然.close(就是關閉一個檔案).read就是來讀取這個檔案的全部內容放到字串contents中。然而這個read函式讀取到最後一行的時候回事空的一行在直接列印contents的時候會有多一行的空行,需要這麼來寫可以省去空行。

with open('readerFile.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
    file_object.close()

當你存放檔案的路徑不在這資料夾裡的時候,你就需要傳入一個精確地檔案路徑。

方法有兩個:

#1
with open('E:/python/day5/filePath/readerFile.txt') as file_object:
   contents = file_object.read()
   print(contents.rstrip())
   file_object.close()

#2 path = 'E:/python/day5/filePath/readerFile.txt' with open(path) as file_object: contents = file_object.read() print(contents.rstrip()) file_object.close()

有時候我們需要一行一行的拿出資料來列印,我們可以使用for迴圈來實現

path = 'E:/python/day5/filePath/readerFile.txt'
with open(path) as file_object:
  for line in file_object:
    
print(line,end="")
path = 'E:/python/day5/filePath/readerFile.txt'
with open(path) as file_object:
  for line in file_object:
    print(line.rstrip())

使用關鍵字with時,open()返回的檔案物件只能在with語句塊中使用,只要是出了with語句塊這個檔案物件就會失效,所以我們可以使用一個列表,這樣在with體外也就能使用了,其中用到了readlines()這個方法,他會把每一行存放到一個列表中,在使用lines把這個列表接過來,這樣lines也就是一個列表了

path = 'E:/python/day5/filePath/readerFile.txt'
with open(path) as file_object:
    lines = file_object.readlines()
for line in lines :
    print(line.rstrip())

我們有時候需要只用檔案中的字串也可以直接儲存到一個字串中,這裡需要去除空格,我們用的時候strip()而不是rstrip().

path = 'E:/python/day5/filePath/readerFile.txt'
with open(path) as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines :
    pi_string += line.strip()
print(pi_string)

我們也可以只打印ip_string中的前幾個字元:

print(pi_string[:7] + "......")  #abcdefg......

#檔案的寫入

使用到了open(引數1,引數2),引數1還是檔案路徑名,引數2是 ‘r’ , 'w' , 'a', 'r+'。‘r’只讀,‘w’是寫入,‘a’是在原有的資料夾裡最後的位置追加內容,‘r+’是讀取和寫入檔案模式

如果使用‘w’的話,千萬小心,因為當這個資料夾裡存在這個檔案了的話。他會把這個檔案清空,在寫入資料。

#給檔案寫入資料
with open('write_file.txt','w') as file_object:
    file_object.write('this is my first write_file\n')

我們有時候可以把可能出現異常的程式碼放在try語句中,如果真的出現錯誤了,就會執行except內的語句塊:其中ZeroDivisionError是關鍵字

try:
    print(5/0)
except ZeroDivisionError:
    print("Zero can't be divide")