📅  最后修改于: 2020-09-20 04:23:45             🧑  作者: Mango
open()
的语法为:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
None
, ' '
'\n'
, 'r'
和'\r\n'
True
(默认值);如果另有规定,将引发例外情况 open()
函数返回一个文件对象,该对象可用于读取,写入和修改文件。
如果找不到该文件,则会引发FileNotFoundError
异常。
# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
由于省略了模式,因此文件以'r'
模式打开;打开阅读。
# opens the file in reading mode
f = open("path_to_file", mode='r')
# opens the file in writing mode
f = open("path_to_file", mode = 'w')
# opens for writing to the end
f = open("path_to_file", mode = 'a')
Python的默认编码为ASCII。您可以通过传递encoding
参数来轻松更改它。
f = open("path_to_file", mode = 'r', encoding='utf-8')
推荐读物: Python文件输入/输出