python生成以及打開json、csv和txt文件的實例
更新時間:2018年11月16日 08:58:54 作者:shannon-Li
今天小編就為大家分享一篇python生成以及打開json、csv和txt文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
生成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("加載完成!")
打開txt文件:
with open("test.txt") as f:
content = f.read()
print("文件內(nèi)容:{}".format(content))
打開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.")
打開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生成以及打開json、csv和txt文件的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pandas如何使用列表和字典創(chuàng)建?Series
這篇文章主要介紹了pandas如何使用列表和字典創(chuàng)建?Series,pandas 是基于NumPy的一種工具,該工具是為解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的,下文我們就來看看文章是怎樣介紹pandas,需要的朋友也可以參考一下2021-12-12
python編程中簡潔優(yōu)雅的推導(dǎo)式示例詳解
這篇文章主要為大家介紹了python編程中簡潔優(yōu)雅的推導(dǎo)式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11
Python?turtle.right與turtle.setheading的區(qū)別講述
這篇文章主要介紹了Python?turtle.right與turtle.setheading的區(qū)別,本文以turtle.right為例給大家詳細介紹,需要的朋友可以參考下2022-03-03
Python使用requests及BeautifulSoup構(gòu)建爬蟲實例代碼
這篇文章主要介紹了Python使用requests及BeautifulSoup構(gòu)建爬蟲,介紹了具體操作步驟和實例代碼等相關(guān)內(nèi)容,小編覺得還是挺不錯的,這里分享給大家,需要的朋友可以參考下2018-01-01

