本文共 2718 字,大约阅读时间需要 9 分钟。
python 示例
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 –这是一个可选参数,用于指定各种文件模式。
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 Exampleprint("creating files...")# creating a file without specifying mode (b or t)file1 = open("hello_1.txt", "w")# creating a file in binary modefile2 = open("hello_2.txt", "wb")# creating a file in text modefile3 = open("hello_3.txt", "wt")print("file creation operation done...")# printing the details of file objectsprint(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 filef = open("hello.txt", "w")print("file created...")print(f) # prints file details# opening created file in read modef = 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 existf = open("myfile.txt") # returns an error
Output
输出量
Traceback (most recent call last): File "main.py", line 4, inf = open("myfile.txt") # returns an errorFileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
翻译自:
python 示例
转载地址:http://avtzd.baihongyu.com/