File I/O refers to the process of reading from and writing to files on your computer. Python provides built-in functions and methods that allow us to work with files easily. Here are some examples: **Reading from a File:** To read from a file, you can use the `open()` function to open the file in read mode (`"r"`), and then use the `read()` method to read the contents of the file. Here's an example:
file = open("example.txt", "r") content = file.read() print(content) file.close()
Hello, world! This is a new line.
In this code, we open the file named `"example.txt"` in read mode and assign it to the `file` variable. We then use the `read()` method to read the contents of the file and store it in the `content` variable. Finally, we print the content and close the file using the `close()` method. **Writing to a File:** To write to a file, you can use the `open()` function to open the file in write mode (`"w"`), and then use the `write()` method to write content to the file. Here's an example:
file = open("example.txt", "w") file.write("Hello, world!") file.close()
In this code, we open the file named `"example.txt"` in write mode and assign it to the `file` variable. We then use the `write()` method to write the string `"Hello, world!"` to the file. Finally, we close the file using the `close()` method. **Appending to a File:** To append content to an existing file, you can use the `open()` function to open the file in append mode (`"a"`), and then use the `write()` method to append content to the file. Here's an example:
file = open("example.txt", "a") file.write("\nThis is a new line.") file.close()
In this code, we open the file named `"example.txt"` in append mode and assign it to the `file` variable. We then use the `write()` method to append the string `"\nThis is a new line."` to the file. The `"\n"` is a special character that represents a new line. Finally, we close the file using the `close()` method. It's important to note that when working with files, it's a good practice to close the file after you're done using it. Alternatively, you can use the `with` statement, which automatically closes the file for you. Here's an example:
with open("example.txt", "r") as file: content = file.read() print(content)
Hello, world! This is a new line.
In this code, the `with` statement opens the file, reads its content, and automatically closes the file when the block of code is finished. These are some basic examples of file I/O in Python. There are many more operations and methods available for working with files, such as reading line by line, handling errors, and working with different file formats.