2.10. Python Language Fundamentals: File Manipulation in Python
The Python language, with its simple and clear syntax, has become one of the most popular programming languages for developing backend applications. One of the many tasks that Python developers frequently perform is file manipulation. In this chapter, we'll explore the basics of file manipulation in Python.
Opening Files
To manipulate a file in Python, the first thing we need to do is open the file. This is done using the 'open()' function, which returns a file object. The 'open()' function accepts two parameters: the file name and the mode.
file = open('example.txt', 'r')
The first parameter is a string containing the file name. The second parameter is another string that contains some characters that describe the way the file will be used. 'r' means the file will be opened for reading (this is the default value), 'w' for writing (truncating the file if it already exists), 'a' for appending (which will add data to the end of the file if it already exists), and 'x' to create a new file.
File Reading
After opening a file for reading, we can use the 'read()' function to read the contents of the file. For example:
file = open('example.txt', 'r') print(file.read())
The 'read()' function reads the entire contents of the file. If you only want to read a certain amount of characters, you can pass the number of characters as an argument to the 'read()' function.
Writing in Files
To write to a file, we open the file in write mode ('w') or in add mode ('a'). We can then use the 'write()' function to add text to the file.
file = open('example.txt', 'w') file.write('Hello, world!')
It is important to remember that the write mode ('w') will erase the entire contents of the file before writing new data. If you want to add data to an existing file without deleting the previous contents, you must open the file in add ('a') mode.
File Closing
When we finish working with a file, we must always close it using the 'close()' function. This frees up system resources that were used while manipulating the file.
file = open('example.txt', 'r') print(file.read()) file.close()
File Manipulation with the 'with' Block
A safer way to manipulate files is using the 'with' block. This ensures that the file is closed correctly, even if an error occurs while manipulating the file.
with open('example.txt', 'r') as file: print(file.read())
With this, we have completed the basics of file manipulation in Python. However, Python offers many other functions and methods for working with files, which you can explore as you become more familiar with the language.