How do you read and write to a file in Python?

 To read and write to a file in Python, you can use the built-in open() function to open the file and then use methods of the resulting file object to read from or write to the file. Here are some examples:

Reading from a file:

To read the contents of a file, you can use the read() method of the file object. For example:


In this example, the open() the function is used with a context manager (with statement) to automatically close the file when the block is exited. Inside the block, the read() method is used to read the entire contents of the file into the contents variable, which is then printed to the console.

Writing to a file:
To write to a file, you can use the write() method of the file object. For example:

In this example, the open() function is used with a context manager to automatically close the file when the block is exited. Inside the block, the write() method is used to write the string "Hello, world!" to the file.

Note that when opening a file for writing, you should use the "w" mode. If the file already exists, this will overwrite its contents. If the file does not exist, it will be created. If you want to append to an existing file, you can use the "a" mode instead. For example:



Comments