带有示例的Python File open()方法

档案open()方式

open()method是Python中的内置方法,用于创建,打开或附加文件。

语法:

    file_object = open(file_name, file_mode)

Parameter(s):

  • file_name –用于指定文件名。

  • file_mode –这是一个可选参数,用于指定各种文件模式。

    • w –以写模式打开文件,即创建文件。

    • r –以读取模式打开文件。

    • a –以追加模式打开文件。

    • x –创建文件,如果文件存在则返回错误。

    • t –用于文件模式以指定文本模式(例如:wt,rt,at和xt)。

    • b –用于文件模式以指定二进制模式(例如:wb,rb,ab和xb)。

返回值:

该方法的返回类型为<class'_io.TextIOWrapper'>,它返回一个文件对象。

范例1:

# 带有示例的Python File open()方法

print("creating files...")
# 创建文件而不指定模式(b或t)
file1 = open("hello_1.txt", "w")

# 以二进制模式创建文件
file2 = open("hello_2.txt", "wb")

# 以文本模式创建文件
file3 = open("hello_3.txt", "wt")

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

# 打印文件对象的详细信息
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()方法

# 创建一个文件
f = open("hello.txt", "w")
print("file created...")
print(f) # 打印文件详细信息

# 以读取模式打开创建的文件
f = open("hello.txt", "r")
print("file opened...")
print(f) # 打印文件详细信息

# 以追加模式打开文件 
f = open("hello.txt", "a")
print("file opened in append mode...")
print(f) # 打印文件详细信息

输出结果

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()方法

# 打开一个不存在的文件
f = open("myfile.txt") # 返回错误

输出结果

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