This is a discussion on Open a File within the Programming forums, part of the Tutorials category; Open a File:- You use the open function in Python to open a file. The open function creates a file ...
Open a File:-
You use the open function in Python to open a file. The open function creates a file object and associates it with a file on the disk. Here is the general format of how the open function is used:
file-variable = open (filename, mode)
In the general format:
1. file-variable is the name of the variable that will reference the file object.
2. filename is a string specifying the name of the file.
3. mode is a string specifying the mode (reading, writing, etc.) in which the file will be opened.
For example, suppose the file customers. txt contains customer data, and we want to open for reading. Here is an example of how we would call the open function:
customer_file = open('cusomters.txt', 'r')
After this statement executes, the file named customers.txt will be opened, and the variable customer_file will reference a file object that we can use to read data from the file.
Suppose we want to create a file named sales.txt and write data to it. Here is an example of how we would call the open function:
sales_file = open('sales.txt', 'w')
After this statement executes, the file named sales.txt will be created, and the variable sales_file will reference a file object that we can use to write data to the file.
Bookmarks