How to read and write files in Python?
Asked by Bob Smith27 days ago
39 views
File operations in Python.
0
1 answers
1 Answer
Reading and writing files in Python is straightforward and commonly done using the built-in `open()` function. This function allows you to open a file and specify the mode in which you want to work with it, such as reading, writing, or appending.
### Reading Files
To read a file, you typically open it in read mode (`'r'`). Here’s a simple example:
```python
# Open a file for reading
with open('example.txt', 'r') as file:
content = file.read() # Read the entire file content
print(content)
```
Using `with` is recommended because it automatically closes the file after the block is executed, even if an error occurs. You can also read a file line-by-line using a loop:
```python
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # Print each line without trailing newline characters
```
### Writing Files
To write to a file, open it in write mode (`'w'`). This will create the file if it doesn’t exist or overwrite it if it does:
```python
with open('output.txt', 'w') as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
```
If you want to add content to the end of an existing file without overwriting, use append mode (`'a'`):
```python
with open('output.txt', 'a') as file:
file.write("\nAppending this line.")
```
### Summary of Common Modes
- `'r'` – Read (default mode)
- `'w'` – Write (overwrite)
- `'a'` – Append
- `'b'` – Binary mode (e.g., `'rb'` or `'wb'` for reading/writing binary files)
These basics cover most file operations in Python. Remember to handle exceptions in production code to manage errors like missing files or permission issues.
0
0
by Olivia Brown15 days ago
