python 示例
文件open()方法 (File open() Method)
open() method is an inbuilt method in Python, it is used to create, open or append a file.
open()方法是Python中的内置方法,用于创建,打开或附加文件。
Syntax:
句法:
file_object = open(file_name, file_mode)
Parameter(s):
参数:
file_name – It is used to specify the file name.
file_name –用于指定文件名。
file_mode – It is an optional parameter, it is used to specify the various file modes.
file_mode –这是一个可选参数,用于指定各种文件模式。
- w – Opens the file in write mode i.e. creates a file.
- w –以写模式打开文件,即创建文件。
- r – Opens the file in reading mode.
- r –以读取模式打开文件。
- a – Opens the file in append mode.
- a –以追加模式打开文件。
- x – Creates the file, if file exists it returns an error.
- x –创建文件,如果文件存在则返回错误。
- t – It is used to file modes to specify the text mode (Example: wt, rt, at, and xt).
- t –用于文件模式以指定文本模式(例如: wt , rt , at和xt )。
- b – It is used to file modes to specify the binary mode (Example: wb, rb, ab, and xb).
- b –用于文件模式以指定二进制模式(例如: wb , rb , ab和xb )。
Return value:
返回值:
The return type of this method is <class '_io.TextIOWrapper'>, it returns a file object.
该方法的返回类型为<class'_io.TextIOWrapper'> ,它返回一个文件对象。
Example 1:
范例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)
Output
输出量
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'>
Example 2:
范例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
Output
输出量
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'>
Example 3:
范例3:
# Python File open() Method with Example
# opening a file that doesn't exist
f = open("myfile.txt") # returns an error
Output
输出量
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'
翻译自: https://www.includehelp.com/python/file-open-method-with-example.aspx
python 示例