Python open() 函数用法

2023-09-17 22:28:39

open() 方法打开文件(如果可能)并返回相应的文件对象。

open() 语法:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数:

  1. file:要打开的文件的路径名或要包装的文件的整数文件描述符。
  2. 模式
  3. :(可选)打开文件时的访问模式。默认模式为"r"表示读取。查看所有access modes
  4. 缓冲
  5. :(可选)用于设置缓冲策略。默认值为 -1。如果指定的模式是二进制"b",则传递 0,
  6. 编码:(可选)用于对文件进行编码或解码的编码格式。
  7. 错误:(可选)指定如何处理编码/解码错误的字符串。
  8. 换行
  9. 符:(可选)说明换行模式的工作方式。它可以是"无"、" "、"r"和"r "。
  10. Closefd:(可选)如果给定文件名,则必须为 True。如果为 False,则文件描述符将在文件关闭时保持打开状态
  11. 打开
  12. 程序:(可选)自定义可调用文件打开程序。

返回类型:

返回文件对象。

文件访问模式

下表列出了文件访问模式参数值。

Access Modes描述
r打开文件以供阅读。
rb以二进制格式打开文件以供仅读取。
r+打开文件以进行读取和写入。
rb+打开二进制格式的读取和写入文件。
w打开文件仅用于写入。
wb打开仅以二进制格式写入的文件。
w+打开文件进行写入和读取。
wb+打开二进制格式的文件以进行写入和读取。
a打开要追加的文件。
ab打开要以二进制格式追加的文件。
a+打开文件以进行追加和读取。
ab+以二进制格式打开用于追加和读取的文件。

下面的示例从当前目录中打开一个文件,以便读取和写入文件。Python shell 中的当前目录是 C:python38

>>> f = open("MyFile.txt") # Open MyFile.txt from the current directory for reading
>>> f = open("MyFile.txt", 'w') # Open MyFile.txt from the current directory for writing
# perform file operations using f
>>> f.close()

如果出现问题,文件操作可能会引发异常。因此,建议使用 try-except-finally 来处理异常和关闭文件对象。

try:
    f = open("MyFile.txt") # Open MyFile.txt from the current directory for reading
    # perform file operations using f
except:
     # handle exceptions
finally:
    f.close()  

下面的示例打开文件以进行读取、写入或更新操作。

>>> f = open("C:MyFile.txt") # open for reading
>>> f = open("C:MyFile.txt",'w') # open for writing 
>>> f = open("C:MyFile.txt", 'x') # open for exclusive creation
>>> f = open("C:MyFile.txt", 'a') # open for writing, appending to the end of file
>>> f = open("C:MyApp.exe", 'b') # open in binary mode for read
>>> f = open("C:myimage.jpg", 'rb') # open file in binary mode for read and write
>>> f = open("C:MyFile.txt", 't') # open in text mode for read
>>> f = open("C:MyFile.txt", mode='r', encoding='utf-8') # open for reading with utf-8 encoding
>>> f = open("C:MyFile.txt", '+') # open for reading or writing
>>> print(type(f)
<class '_io.TextIOWrapper'>
>>> f.close() # closing file after file operations

访问working with files in Python了解更多信息。