Home > Article > Backend Development > How to use the open() function to open a file in Python 2.x
How to use the open() function to open a file in Python 2.x
In the Python 2.x version, you can use the open() function to open and operate files. The open() function accepts two parameters: file name and open mode. The filename can be a relative or absolute path, and the opening mode determines how the file is manipulated. The following will introduce the usage of the open() function and provide some sample code.
Open mode:
The sample code is as follows:
file = open('example.txt', 'r') content = file.read() print(content) file.close()
file = open('example.txt', 'w') file.write('Hello, world!') file.close()
file = open('example.txt', 'a') file.write(' This is a new line.') file.close()
file = open('example.txt', 'r') for line in file: print(line) file.close()
with open('example.txt', 'r') as file: content = file.read() print(content)
It should be noted that after using the open() function to open a file, it is best to close the file after the operation is completed to release resources and avoid potential errors. You can use the close() method to close the file, or use the with statement, which will automatically close the file.
In addition, when processing files, you can also use other related methods to operate files, such as readline(), readlines(), write(), etc. Choose the appropriate method according to specific needs.
Summary: The above is how to use the open() function in Python 2.x, including the mode of opening files and some common operations. Through these sample codes, you can better understand how to use the open() function in Python to open and operate files. Remember to close files after working on them to develop good habits.
The above is the detailed content of How to use the open() function to open a file in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!