當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python File open()用法及代碼示例

文件 open() 方法

open() 方法是 Python 中的內置方法,用於創建、打開或附加文件。

用法:

    file_object = open(file_name, file_mode)

參數:

  • file_name- 用於指定文件名。
  • file_mode- 它是一個可選參數,用於指定各種文件模式。
    • w- 以寫模式打開文件,即創建一個文件。
    • r- 以閱讀模式打開文件。
    • a- 以追加模式打開文件。
    • x- 創建文件,如果文件存在則返回錯誤。
    • t- 用於文件模式以指定文本模式(例如:wtrtatxt)。
    • b- 用於文件模式以指定二進製模式(例如:wbrbabxb)。

返回值:

這個方法的返回類型是<class '_io.TextIOWrapper'>,它返回一個文件對象。

範例1:

# Python File open() Method with Example

print("creating files...")
# creating a file without specifying mode (b or t)
file1 = open("hello_1.txt", "w")

# creating a file in binary mode
file2 = open("hello_2.txt", "wb")

# creating a file in text mode
file3 = open("hello_3.txt", "wt")

print("file creation operation done...")

# printing the details of file objects
print(file1)
print(file2)
print(file3)

輸出

creating files...
file creation operation done...
<_io.TextIOWrapper name='hello_1.txt' mode='w' encoding='UTF-8'>
<_io.BufferedWriter name='hello_2.txt'>
<_io.TextIOWrapper name='hello_3.txt' mode='wt' encoding='UTF-8'>

範例2:

# Python File open() Method with Example

# creating a file
f = open("hello.txt", "w")
print("file created...")
print(f) # prints file details

# opening created file in read mode
f = open("hello.txt", "r")
print("file opened...")
print(f) # prints file details

# opening file in append mode 
f = open("hello.txt", "a")
print("file opened in append mode...")
print(f) # prints file details

輸出

file created...
<_io.TextIOWrapper name='hello.txt' mode='w' encoding='UTF-8'>
file opened...
<_io.TextIOWrapper name='hello.txt' mode='r' encoding='UTF-8'>
file opened in append mode...
<_io.TextIOWrapper name='hello.txt' mode='a' encoding='UTF-8'>

範例3:

# Python File open() Method with Example

# opening a file that doesn't exist
f = open("myfile.txt") # returns an error

輸出

Traceback (most recent call last):
  File "main.py", line 4, in <module>
   f = open("myfile.txt") # returns an error
FileNotFoundError:[Errno 2] No such file or directory:'myfile.txt'   


相關用法


注:本文由純淨天空篩選整理自 Python File open() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。