Python read file
You can use Python to read files. There are open()
and read()
functions for that. They are Python built-in, so no need to install or import of additional modules.
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.
We will read and display contents of documents/todo.txt
file. Here is the file output:
# TODO
- [ ] clean desk
- [ ] water flowers
- [ ] check github issues
Yes, it is my TODO list ๐
# initialize variable
content = ''
# open a file in read mode
with open(r"/home/piotr/documents/todo.txt", "r") as fin:
content = fin.read()
# display file content
print(content)
Summary
We have read and displayed the exact output of file todo.txt
. Please note that we have used the full path to the file. It is my prefered way. However, you can also specify relative path, for example ../documents/todo.txt
. Then, the working directory will be used as starting directory to find the file path. If you pass just the file name, then current working directory will be used.
The power of Python in file operations is great when you need to deal with many (>100s) files.
Recipes used in the python-read-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-read-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.
Similar notebooks
List of similar Python notebooks, so you can find more inspiration ๐