eolas/neuron/233bf7c7-59e9-471c-8275-895571468b75/Writing_to_files_in_Python.md

33 lines
767 B
Markdown
Raw Normal View History

2024-10-25 09:51:23 +01:00
---
tags: [python, file-system, procedural]
created: Friday, October 25, 2024
---
# Writing to files in Python
We create a file object with `open()` and use the `write` method:
```py
# Open file in write mode
file = open("example.txt", "w")
# Write some text to the file
file.write("Hello, this is an example text written using Python.")
# Close the file
file.close()
```
Alternatively we use `with open` which automatically closes the file:
```py
with open("example.txt", "w") as file
file.write('some lines')
```
> Note that in the above example, if the file does not already exist, it will
> create it. If it does exist, it will overwrite its contents with the new data.
> So we use `write` to create new files as well as to write to existing files.