文件
fileName = "pi_digits.txt"
with open(fileName) as fileObj:
contents = fileObj.read()
fileObj = open(fileName)
contents = fileObj.read()
fileObj.close()
print(contents)
with open(fileName) as fileObj:
for line in fileObj:
print(f"$${line.strip()}")
with open(fileName) as fileObj:
lines = fileObj.readlines()
for line in lines:
print(f"<< {line.strip()}")
outputName = "output.txt"
with open(outputName, "w") as fileObj:
fileObj.write("123\n")
fileObj.write("456\n")
with open(outputName, "a") as fileObj:
fileObj.write("789")
异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divided by zero")
else:
print("Success")
try:
print(5/0)
except ZeroDivisionError:
pass
Json
import json
array = [1, 2, 3]
with open("array.json", "w") as file:
json.dump(array, file)
with open("array.json") as file:
newArray = json.load(file)
print(newArray)