python生成以及打开json、csv和txt文件的实例

yipeiwu_com5年前Python基础

生成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("文件内容:{}".format(content))

打开json文件:

import json
import sys


with open("test.json") as f:
 try:
  content = json.load(f)
  print("文件内容:{}".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("文件内容:".format(content))
 except csv.Error as e:
  sys.exit("file %s, line %d: %s" % (f, reader.line_num, e))

以上这篇python生成以及打开json、csv和txt文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python设置Socket代理及实现远程摄像头控制的例子

为python设置socket代理 首先,你得下载SocksiPy这个.解压出来之后里面会有一个socks.py文件.然后你可以把这个文件复制到python安装目录里面的Lib\site...

python3的url编码和解码,自定义gbk、utf-8的例子

因为很多时候要涉及到url的编码和解码工作,所以自己制作了一个类,废话不多说 码上见! # coding:utf-8 import urllib.parse class Ur...

Python常用库大全及简要说明

环境管理 管理 Python 版本和环境的工具 p:非常简单的交互式 python 版本管理工具。官网 pyenv:简单的 Python 版本管理工具。官网 Vex:可以在虚拟环境中...

python同步两个文件夹下的内容

本文实例为大家分享了python同步两个文件夹下的内容,供大家参考,具体内容如下 import os import shutil import time import logging...

Python装饰器基础概念与用法详解

本文实例讲述了Python装饰器基础概念与用法。分享给大家供大家参考,具体如下: 装饰器基础 前面快速介绍了装饰器的语法,在这里,我们将深入装饰器内部工作机制,更详细更系统地介绍装饰器的...