一、Python寫入Json文件換行
Json文件以文本方式存儲,如果想讓Json文件中的數據換行,可以在寫入Json文件時添加indent
參數指定縮進大小。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with open("data.json", "w", encoding="utf-8") as f:
f.write(json.dumps(data, indent=4))
二、Python創建Json文件並寫入
如果要將數據寫入Json文件,需要先創建Json文件。Python提供了open()
函數來創建文件。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
三、Python寫入Json文件亂碼
在寫入Json文件時,可能會遇到亂碼問題。一般情況下,這是由於編碼問題引起的。
可以在open()
函數中指定文件編碼,或者使用codecs
模塊打開Json文件。
示例代碼:
import json
import codecs
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with codecs.open("data.json", "w", "utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
四、Python寫入Json文件編碼問題
Json文件默認使用Unicode編碼。如果需要使用其他編碼,可以在json.dumps()
函數中指定編碼。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with open("data.json", "w", encoding="gbk") as f:
f.write(json.dumps(data, indent=4, ensure_ascii=False).encode("gbk").decode("gbk"))
五、Python寫入Json文件不識別中文
在寫入Json文件時,如果Json文件不識別中文,可以使用ensure_ascii=False
參數。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"編程",
"閱讀",
"旅遊"
]
}
with open("data.json", "w", encoding="utf-8") as f:
f.write(json.dumps(data, indent=4, ensure_ascii=False))
六、Python讀Json文件
Python可以使用json.load()
函數從Json文件中讀取數據。
示例代碼:
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data)
七、Python寫入Json文件怎麼換行
在寫入Json文件時,可以在json.dump()
函數中指定indent
參數的大小。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
八、Python寫入Json文件帶縮進
在寫入Json文件時,可以在json.dump()
函數中指定indent
參數的大小,實現帶縮進的效果。
示例代碼:
import json
data = {
"name": "Tom",
"age": 18,
"hobbies": [
"coding",
"reading",
"traveling"
]
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
九、Python寫入Txt文件
除了寫入Json文件,Python也可以寫入Txt文件。
示例代碼:
data = "Hello, world!"
with open("data.txt", "w", encoding="utf-8") as f:
f.write(data)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/257341.html