python生成以及打開(kāi)json、csv和txt文件的實(shí)例
生成txt文件:
mesg = "hello world"
with open("test.txt", "w") as f:
f.write("{}".format(mesg))
print("加載完成!")
生成json文件:
import json
mesg = {"key": "value"}
with open("test.json", "w") as f:
json.dump(mesg, f)
print("加載完成!")
生成csv文件:
import csv
with open("test.csv", "w") as f:
fieldnames = ["name", "age"] # 表的列名
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() # 加上表頭
writer.writerow({"name": "shannon-li", "age": 4}) # 按行添加
print("加載完成!")
打開(kāi)txt文件:
with open("test.txt") as f:
content = f.read()
print("文件內(nèi)容:{}".format(content))
打開(kāi)json文件:
import json
import sys
with open("test.json") as f:
try:
content = json.load(f)
print("文件內(nèi)容:{}".format(content))
except TypeError:
sys.exit("Error on load json file.")
打開(kāi)csv文件:
import csv
import sys
content = []
with open("test.csv") as f:
reader = csv.DictReader(f, delimiter=",", quotechar="|")
try:
for row in reader:
content.append({"name": row["name"], "age": row["age"]})
print("文件內(nèi)容:".format(content))
except csv.Error as e:
sys.exit("file %s, line %d: %s" % (f, reader.line_num, e))
以上這篇python生成以及打開(kāi)json、csv和txt文件的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
pandas如何使用列表和字典創(chuàng)建?Series
這篇文章主要介紹了pandas如何使用列表和字典創(chuàng)建?Series,pandas 是基于NumPy的一種工具,該工具是為解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的,下文我們就來(lái)看看文章是怎樣介紹pandas,需要的朋友也可以參考一下2021-12-12
python編程中簡(jiǎn)潔優(yōu)雅的推導(dǎo)式示例詳解
這篇文章主要為大家介紹了python編程中簡(jiǎn)潔優(yōu)雅的推導(dǎo)式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
開(kāi)啟Django博客的RSS功能的實(shí)現(xiàn)方法
這篇文章主要介紹了開(kāi)啟Django博客的RSS功能的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Python?turtle.right與turtle.setheading的區(qū)別講述
這篇文章主要介紹了Python?turtle.right與turtle.setheading的區(qū)別,本文以turtle.right為例給大家詳細(xì)介紹,需要的朋友可以參考下2022-03-03
Python使用requests及BeautifulSoup構(gòu)建爬蟲(chóng)實(shí)例代碼
這篇文章主要介紹了Python使用requests及BeautifulSoup構(gòu)建爬蟲(chóng),介紹了具體操作步驟和實(shí)例代碼等相關(guān)內(nèi)容,小編覺(jué)得還是挺不錯(cuò)的,這里分享給大家,需要的朋友可以參考下2018-01-01
jupyter代碼塊沒(méi)有運(yùn)行圖標(biāo)的解決方案
這篇文章主要介紹了jupyter代碼塊沒(méi)有運(yùn)行圖標(biāo)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04

