Python open()函数
Python open()函数用于 open() 内部存储的文件。它将文件的内容作为Python对象返回。
Syntax: open(file_name, mode)
Parameters:
file_name: This parameter as the name suggests, is the name of the file that we want to open.
mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:
- “r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists.
- “w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you.
- “a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you.
- “x”: This string is used to create a specific file.
- “b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files.
- “t”: This string is used to handle files in text mode. By default, the open() function uses the text mode.
示例 1:创建文本文件
以下代码可用于创建文件。在这里,我们将创建一个名为“geeksforgeeks.txt”的文本文件。
Python3
created_file = open("geeksforgeeks.txt","x")
# Check the file
print(open("geeksforgeeks.txt","r").read() == False)
Python3
my_file = open("geeksforgeeks.txt", "w")
my_file.write("Geeksforgeeks is best for DSA")
my_file.close()
#let's read the contents of the file now
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
Python3
my_file = open("geeksforgeeks.txt","a")
my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")
my_file.close()
# reading the file
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
输出:
True
示例 2:读取和写入文件
在这里,我们将以下字符串写入我们刚刚创建的geeksforgeeks.txt文件并再次读取同一个文件。
Geeksforgeeks is best for DSA
下面的代码可用于相同的:
蟒蛇3
my_file = open("geeksforgeeks.txt", "w")
my_file.write("Geeksforgeeks is best for DSA")
my_file.close()
#let's read the contents of the file now
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
输出:
Geeksforgeeks is best for DSA
示例 3:将内容附加到文件
在这里,我们将以下文本附加到 geeksforgeeks.txt 文件并再次读取相同内容:
蟒蛇3
my_file = open("geeksforgeeks.txt","a")
my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")
my_file.close()
# reading the file
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
输出:
Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<..
注意: “w”和“r”之间的区别在于,一个覆盖现有内容,而后者将内容添加到现有文件中,保持内容不变。