Creating and writing to files in Python is a fundamental operation.
Here are examples demonstrating how to write and create files:
Writing to a New File:
```python
# Open a file in write mode (creates a new file if it doesn't exist)
with open("new_file.txt", "w") as file:
file.write("This is a new file with some content.")
```
Writing Multiple Lines to a File:
```python
# Open a file in write mode
with open("multiline_file.txt", "w") as file:
lines = ["Line 1: Example content.", "Line 2: More content."]
file.write("\n".join(lines))
``
Appending to an Existing File:
```python
# Open a file in append mode (creates a new file if it doesn't exist)
with open("existing_file.txt", "a") as file:
file.write("\nAppending additional content to the file.")
```
Writing Binary Data to a File:
```python
# Open a file in binary write mode
with open("binary_file.bin", "wb") as file:
data = bytearray([65, 66, 67, 68, 69]) # Binary data: ABCDE
file.write(data)
```
Using `writelines()` to Write a List of Lines:
```python
# Open a file in write mode
with open("list_file.txt", "w") as file:
lines = ["Line 1: Example content.", "Line 2: More content."]
file.writelines('\n'.join(lines))
```
These examples cover various scenarios for creating and writing to files. The `with` statement is used to ensure that the file is properly closed after writing. Writing can be done in text mode or binary mode, and you can write data at once or line by line. The `writelines()` method allows you to write a list of lines to a file.
0 Comments