Working with files in Python
Python provides built-in methods to create and modify files. File-related Python operations are useful in a large number of programming exercises. These methods are provided by standard Python modules and do not require installation of additional packages.
The open() method
The open()
method is a default method that is available in Python and it is one of the most widely used functions to manipulate files. Now, the first step of dealing with a file is to open it:
>>> f = open('test.txt', 'w')
This command will create a test.txt
file in the same folder in which you started the Python interpreter or the location from where the code is being executed. The preceding command uses the w
mode that opens a file for writing or creates a new one if it doesn't exist. The other modes that can be used with the open()
function are displayed in the following table:
Mode |
Description |
---|---|
|
This opens or creates a file for writing only. It overwrites an existing file. ... |