Python -Create, write and read file -VS Code on Ubuntu No.35

How to create, write and read a file using Python in Visual Studio Code on Ubuntu is shown in this blog.

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.

ModeDescription
‘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

That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *