Reading and Writing Files

Reading and writing files is a common task in programming, as it allows you to store and retrieve data from disk. In Python, you can read and write files using the built-in open function.

The open function takes the name of a file and a mode as arguments and returns a file object, which you can then use to read or write to the file. The most common modes are 'r' for reading and 'w' for writing.

For example, to read the contents of a file, you can use the following code:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

In this example, the open function is used to open the file 'example.txt' in reading mode. The with statement is used to ensure that the file is automatically closed after the block of code is executed. The read method is then called on the file object, which returns the contents of the file as a string. The contents are then printed to the console.

To write to a file, you can use the following code:

with open('example.txt', 'w') as file:
    file.write('Hello, World!')

In this example, the open function is used to open the file 'example.txt' in writing mode. The with statement is used to ensure that the file is automatically closed after the block of code is executed. The write method is then called on the file object, which writes the string 'Hello, World!' to the file.

It is also possible to append to a file by using the 'a' mode instead of the 'w' mode.

In conclusion, reading and writing files is a fundamental aspect of programming in Python. By using the open function and methods like read and write, you can easily read from and write to files, allowing you to store and retrieve data from disk.