Python File Opening
In python, the built-in open() function is the crucial function to work with the files. To perform any file-related operations such as creating the file, writing the file, reading the file, etc., you need to use an open() function.
The built-in open() function is useful to open the physical file and map to the file object to perform the file-related operations in python.
Following is the syntax of defining the open() function in python to open the files.
The open() function will accept two parameters; those are
- filename - It's the file's name, including the file path.
- mode - The mode parameter is useful to indicate the purpose of opening the file, e.g., read, write, etc., and it's optional.
The following table lists the different modes available in python to perform create, write, update, and delete operations on files in python.
Python Open File to Write the Data
Following is the example of opening the file to write the data in python.
file.write("Welcome to Tutlane")
file.close()
To learn more about writing the files in python, refer to Python writing data to the files.
Python Open File to Read the Data
Same way, you can use the open() function to open and read the data from a file.
print(file.read())
#or
file = open("testfile.txt", "r")
print(file.read())
For file reading operation, it's enough to mention the file name. By default, the open() will function consider using mode as "r".
The above examples wrote by considering the file (testfile.txt) that exists in the same python location. If the file is in a different location, you need to specify the complete file path to write or read the file as shown below.
print(file.read())
In python, you can read the data from a file in different ways. You can learn more about it in Python read data from the file.
Python File Methods
Like, write(), read(), etc., the file object has different methods to perform the file-related operations in python.
In the next chapters, we will learn more about creating, writing, reading, and deleting files in python.
