Reading and writing files in Python

In Python, you can read and write files using the built-in functions `open()` and `close()`. The `open()` function is used to open a file and returns a file object, which you can then use to read or write data to the file. The `close()` function is used to close the file when you are done working with it.

Here’s an example of how to open a file for reading and read its contents:

python
# Open the file in read mode
file = open('example.txt', 'r')

# Read the contents of the file
contents = file.read()

# Print the contents of the file
print(contents)

# Close the file
file.close()

In this example, we first use the `open()` function to open a file called `example.txt` in read mode (`’r’`). We then use the `read()` method of the file object to read the contents of the file into a variable called `contents`. Finally, we print the contents of the file and close the file using the `close()` function.

To write data to a file, you can use the `write()` method of the file object. Here’s an example:

python
# Open the file in write mode
file = open('example.txt', 'w')

# Write some content to the file
file.write('This is some new content.')

# Close the file
file.close()

In this example, we open the same file `example.txt`, but this time in write mode (`’w’`). We then use the `write()` method to write the string `’This is some new content.’` to the file. Finally, we close the file using the `close()` function. Note that when you open a file in write mode, any existing content in the file will be overwritten. If you want to append new content to the end of an existing file, you can open the file in append mode (`’a’`) instead.