文件 open() 方法
open() 方法是 Python 中的内置方法,用于创建、打开或附加文件。
用法:
file_object = open(file_name, file_mode)
参数:
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() 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 tell()用法及代码示例
- Python File seek()用法及代码示例
- Python File flush()用法及代码示例
- Python File write()用法及代码示例
- Python File read()用法及代码示例
- Python File truncate()用法及代码示例
- Python File fileno()用法及代码示例
- Python File isatty()用法及代码示例
- Python File writable()用法及代码示例
- Python File writelines()用法及代码示例
- Python File readable()用法及代码示例
- Python File readlines()用法及代码示例
- Python File close()用法及代码示例
- Python File readline()用法及代码示例
- Python File seekable()用法及代码示例
- Python numpy.less()用法及代码示例
- Python Sympy Permutation.list()用法及代码示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代码示例
- Python numpy.tril()用法及代码示例
- Python Matplotlib.pyplot.matshow()用法及代码示例
注:本文由纯净天空筛选整理自 Python File open() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。