Python write file

Python can be used to write content to file. There are built-in functions open() and write(). The new file will appear in the selected directory.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

Let's use documents directory in this notebook :)

documents/
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

We will add a new file ideas.txt in the documents directory.

# import packages
import os
# construct file path
fname = os.path.join(r"/home/piotr/documents", "ideas.txt")
# open a file in write mode
# new file will be created if doesnt exist
# if file exists then it will be overwritten
with open(fname, "w") as fout:
    fout.write("Write notebook about OpenAI API for image generation.")
print("File written successfully")

Summary

The documents directory after running above code:

documents/
├── ideas.txt
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

You can see that there is a new file ideas.txt in the documents directory. If we run the above code few times, then each time the whole file will be overwritten with new content.

Files can be opened in text and binary format. Which format to choose? Text file is best for small data volumes and is human readble. When you need to store large data volumes I would recommend binary format.

Recipes used in the python-write-file.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-write-file.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.