How to create, write and read a file using Python in Visual Studio Code on Ubuntu is shown in this blog.
Contents
▼1. Creating, write and read a file using Python
open() function is used to create a file or edit a file. there are 2 elementary parameters of open() Python function for specifying a file name and the mode of a file operation.
There are some modes as below.
| Mode | Description |
| ‘r’ | open for reading (default) |
| ‘w’ | open for writing, truncating the file first |
| ‘x’ | open for exclusive creation, failing if the file already exists |
| ‘a’ | open for writing, appending to the end of file if it exists |
| ‘b’ | binary mode |
| ‘t’ | text mode (default) |
| ‘+’ | open for updating (reading and writing) |
▼2. Prerequisites
Creating the environment of running python is shown in Python – Using Visual Studio Code on Ubuntu No.34
▼3. Creating a JSON file and then reading it by Python
3-1. Creating a JSON file
such data is generated.
[{"LastName":"Travase","id":"7"},{"LastName":"Ken","id":"8"}]
3-2. Creating, writing and reading a JSON file using Python code
# wrjs.py
import json
dictionary=[{"LastName":"Travase","id":"7"},{"LastName":"ken","id":"8"}]
# creating a json file
with open("sample.json","w") as jsfile:
json.dump(dictionary,jsfile,indent=2)
jsfile.close()
#reading a json file
with open("sample.json","r") as jsofile:
#data=json.load(jsofile)
data=jsofile.read()
jsofile.close()
print(data)
3-3. Runnig writes.py
“sample.json” file is generated by this code.
/bin/python3 wrjsf.py
(sample.json")
[
{
"LastName": "Travase",
"id": "7"
},
{
"LastName": "ken",
"id": "8"
}
]
▼4. Reference
- 7.2. Reading and Writing Files: 7. Input and Output — Python 3.9.6 documentation
- 7.2.2. Saving structured data with json: 7. Input and Output — Python 3.9.6 documentation
That’s all. Have a nice day ahead !!!