/ W3SCHOOLS

W3schools - Python_JSON / File

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

JSON

Is a syntax for storing and exchanging data

Is text, written with JS object notaion

Python has a built-in package called json, which can be used to work with JSON data

# JSON to Python
import json

# some json
x = {name : Sponge, age : 20, city : Bikini city}

# parse json
y = json.loads(x)

# result is a Python dictionary
print(y[name])	# output “Sponge”

# Python to JSON
import json

# dict
x = {name : Sponge, age : 20, city : Bikini city}

# convert into JSON
y = json.dumps(x)

# result is a JSON string
print(y)

Convert from Python to JSON

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

Format the result

json.dumps() has parameters to make it easier to read the result

Use indent to define the number of indents

Use separators to change the default separator

Use sort_keys to specify if the result should be sorted or not

json.dumps(x, indent=4, separators=(., =))
json.dumps(x, indent=4, sort_keys=True)

Try Except

When an error occurs, or exception as we call it, Python will normally stop and generate an error msg

  • these exceptions can be handled using the try
try:
    # lets you test a block of code for error
except:
    # lets you handle the error
    # Can define as may exception blocks as you want
else:
    # lets you execute code when there is no error
finally:
    # lets you execute code, regardless of the result of the try and except blocks

File Handling

open() returns a file object

open() takes two parameters, filename, and mode

mode

  • “r” : Read, Default value. Opens a file for reading, error if the file doesn’t exist

  • “a” : Append, Opens a file for appending, creates the file if it doesn’t exist

  • “w” : Write, Opens a file for writing, creates the file if it doesn’t exist

  • “x” : Create, Creates the specified file, returns an error if the file exist

In addition can specify if the file should be handled as binary or text mode

  • “t” : Text, Default value

  • “b” : Binary : Binary mode, e.g. img

# To open a file for reading
f = open(testfile.txt, rt)
# It is enough to specify the name of file, because r and t are default values
f = open(testfile.txt)

Read

# In testfile.txt
Hello!!
My friend!

# In read.py

# read the content of the file, if the file is located in a different location, will have to specify the file path
f = open(testfile.txt, r)
print(f.read())		# output “Hello!! \n My friend!”
# specify how many characters want to return
print(f.read(5))	# output “Hello”
# return one line
print(f.readline())	# output “Hello!!”
# By calling two times, can read the two first lines
print(f.readline())	# output “My friend!”
f.close()	# always close the file when be done with it

Write

To write to an existing file, must add a parameter to the open()

  • “a” : Append, will append to the end of the file

  • “w” : Write, will overwrite any existing content

# Append
f = open(test.txt, a)
f.write(more content!”)
f.close()

# Write
f = open(test.txt, w)
f.write(overwrite content!”)
f.close()

Delete

To delete a file, must import the os module, and run its os.remove()

# Delete file
import os
if os.path.exists(test.txt):
    os.remove(test.txt)
else:
    print(The file does not exist)

# Delete folder
import os
os.rmdir(myfolder)	# only remove empty folders