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

yipeiwu_com6年前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设计】。

相关文章

Django中URL的参数传递的实现

在Django中有非常强大的URL模块,可以按照开发者的想法来制定清晰的URL,同时支持正则表达式。此外,在URL中还可以传递参数。 1. Django处理请求的方式 1)&n...

python linecache 处理固定格式文本数据的方法

小程序大功能 对一批报文要处理要处理里面的得分,发现python linecache ,特记录如下。 #!/usr/bin/env python # -*- coding: utf-...

Python使用base64模块进行二进制数据编码详解

前言 昨天团队的学妹来问关于POP3协议的问题,所以今天稍稍研究了下POP3协议的格式和Python里面的poplib。而POP服务器往回传的数据里有一部分需要用到Base64进行解码,...

python备份文件以及mysql数据库的脚本代码

复制代码 代码如下: #!/usr/local/python import os import time import string source=['/var/www/html/xxx...

python输出当前目录下index.html文件路径的方法

本文实例讲述了python输出当前目录下index.html文件路径的方法。分享给大家供大家参考。具体实现方法如下: import os import sys path = os.p...