close function

Python 教學 3 – File Handling -Read File, Write File

筆記一下在 Python 中讀寫檔案的方式

1. open Function – 針對檔案做操作

Python 提供了 open function 可以針對檔案進行一些操作:

open(filename, mode)

1.1 filename

第一個參數是 filename,可以是相對路徑也可以是絕對路徑。

1.2 mode

用來決定開啟檔案的用途:

"r" - Read,default value,讀取檔案,如果檔案不存在會噴錯
"a" - Append,將資料 append 到該檔案,如果檔案不存在會直接建立檔案
"w" - Write,將資料覆寫到該檔案,如果檔案不存在會直接建立檔案
"x" - Create,建立檔案,如果檔案已經存在會噴錯

也可以決定要用什麼模式開啟檔案:

"t" - Text,default value,純文字模式
"b" - Binary,二進位模式(ex: 讀取圖片時)
# ex
f = open("test.txt")

f = open("test.txt", "rt")

2. Read File – 讀取檔案

2.1 read function

假設有一個 test.txt 檔:

Hello
World
!!!

可以用 read function 來讀取檔案

f = open("test.txt", "r")
print(f.read())
Hello
World
!!!

read function 也可以傳入 argument 用來決定要 read 幾個 characters:

f = open("test.txt", "r")
print(f.read(3))
Hel

2.2 readline function

用來讀取行數

f = open("test.txt", "r")
print(f.readline())
Hello

執行幾次 readline 就會印出前幾行:

f = open("test.txt", "r")
print(f.readline())
print(f.readline())
Hello

World

2.3 readlines function

會把每一行作為字串,塞到 list 後 return

f = open("test.txt", "r")
print(f.readlines())
['Hello\n', 'World\n', '!!!\n']

3. close function – 關閉檔案

當操作完檔案(不管讀取或寫入),都要記得呼叫 close function,原因如下

  • 當用程式打開檔案的時候,file system 通常會將檔案鎖住,直到用 close function 關閉前,其他程式或 process 都無法使用這個檔案
  • file system 能打開的檔案有限制,要是有太多檔案都沒被正確關閉的話,可能導致系統資源耗盡
  • 當有多個 process 要同時對一個未關閉的檔案做操作時,可能會有 race condition 的情況發生

用 f.close 關閉檔案

f = open("test.txt", "r")
# 針對檔案做某些操作後
...
f.close()

如果希望檔案做完某些操作後可以自動關閉,可以用以下的寫法:

with open("test.txt", "r") as f:
  contents = f.readlines()
  print(contents)

4. Write File – 寫入檔案

4.1 append

可以用 append mode,將內容新增到檔案上:

with open("test.txt", "a") as f:
  f.write('more content!')

with open("test.txt", "r") as f:
  content = f.read()
  print(content)
Hello
World
!!!
more content!

4.2 write

將內容覆寫檔案:

with open("test.txt", "w") as f:
  f.write("I'm new content!")

with open("test.txt", "r") as f:
  content = f.read()
  print(content)
I'm new content!

4.3 create

mode x 用來建立檔案,若檔案存在會直接噴錯

# 新增 myfile.txt 檔
f = open("myfile.txt", "x")

# 因為 test.txt 已經存在,所以會噴錯
f = open("test.txt", "x")
Traceback (most recent call last):
  File "/Users/jimmy/Desktop/Project/python-read-file/main.py", line 1, in <module>
    f = open("test.txt", "x")
        ^^^^^^^^^^^^^^^^^^^^^
FileExistsError: [Errno 17] File exists: 'test.txt'

5. Delete File – 刪除檔案

5.1 delete a file

import os
os.remove("myfile.txt")
# myfile.txt 被刪掉了

5.2 check if file exist

import os
if os.path.exists("myfile.txt"):
    os.remove("myfile.txt")
else:
    print("the file does not exist")
the file does not exist

5.3 delete directory

import os
os.rmdir("myfolder")

6. 參考資料

How to Read a Text file In Python Effectively
Python File Open – W3Schools

如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top