code:
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 14:30:55 2023
@author: SavingKing
"""
sample_dict = {
"name": "Alice",
"age": 30,
"city": "Wonderland"
}
import json
# 直接将字典序列化到文件
with open("output_with_dump.json", "w") as file:
json.dump(sample_dict, file, indent=4)
# 先将字典序列化为字符串,然后写入文件
json_str = json.dumps(sample_dict, indent=4)
with open("output_with_dumps.json", "w") as file:
file.write(json_str)code & 輸出結果:

两个文件 output_with_dump.json 和 output_with_dumps.json 将包含相同的JSON内容,但是生成这些文件的过程不同。json.dump() 是一步到位的方法,直接将对象写入文件;而json.dumps() 则是一个两步的过程,先创建字符串,然后将其写入文件。在结果上,两者是等效的:

推薦hahow線上學習python: https://igrape.net/30afN
![Python: 如何用numpy.ndarray的reshape 將3D array轉為2D array,再轉為pandas.DataFrame? arr.reshape( arr.shape[0] * arr.shape[1] , -1) Python: 如何用numpy.ndarray的reshape 將3D array轉為2D array,再轉為pandas.DataFrame? arr.reshape( arr.shape[0] * arr.shape[1] , -1)](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230320082325_85.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python 如何做excel的樞紐分析? pandas.pivot_table() 或 pandas.DataFrame .groupby() ; 如何指定欄位順序? DataFrame.reindex() ; .sortlevel() ; DataFrame[[col1, col2, col3 ]] ; df.columns.map() ; 如何顯示所有欄? pandas.set_option (“display.max_columns”, None) Python 如何做excel的樞紐分析? pandas.pivot_table() 或 pandas.DataFrame .groupby() ; 如何指定欄位順序? DataFrame.reindex() ; .sortlevel() ; DataFrame[[col1, col2, col3 ]] ; df.columns.map() ; 如何顯示所有欄? pandas.set_option (“display.max_columns”, None)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230323101848_80.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![「Python 的兩條路」:一次搞懂 sys.path (找 .py) 與 os.environ[‘PATH’] (找 .exe) 的愛恨情仇 「Python 的兩條路」:一次搞懂 sys.path (找 .py) 與 os.environ[‘PATH’] (找 .exe) 的愛恨情仇](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2026/01/20260114094100_0_424ead.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![別把中文洗掉:Python `isalnum()` vs `[^A-Za-z0-9]` 含/不含 CJK中日韓 別把中文洗掉:Python `isalnum()` vs `[^A-Za-z0-9]` 含/不含 CJK中日韓](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2026/05/20260525082752_0_4776cd.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


近期留言