我爱编程python自学程序员技术栈

python文件读写(一)-txt, log, json,

2018-07-09  本文已影响70人  Godric_wsw

1.概述

2.txt, log文件读写

1)写:

with open("test.txt","w") as f:
    f.write("test string")

2)读:

with open("test.txt","r") as f:
    print(f.read())

3)注意事项:

4)Python读取大文件(GB级别):

#内存分配交给python解释器处理,读取效率很高,且占用资源少
with open("test.txt","r") as f:
    for line in f:
       print(line)

3.json文件读写

1)写:

import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict,indent=4,sort_keys=True)
with open('test.json',"w") as f:
    f.write(json_str)

2)读:

import json
with open('test.json',"r") as f:
    json_dic = json.load(f)
    print(json_dic["bigberg"])

4.csv文件读写

1)写:

import csv
# 使用数字和字符串的数字都可以
datas = [['name', 'age'],
         ['Bob', 14],
         ['Tom', 23],
        ['Jerry', '18']]
with open('example.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for row in datas:
        writer.writerow(row)

2)读:

import csv
with open("example.csv",'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(reader.line_num, row)

1)写:

import csv
headers = ['name', 'age']
datas = [{'name':'Bob', 'age':23},
        {'name':'Jerry', 'age':44},
        {'name':'Tom', 'age':15}
        ]
with open('example.csv', 'w', newline='') as f:
    # 表头在这里传入,作为第一行数据
    writer = csv.DictWriter(f, headers)
    writer.writeheader()
    for row in datas:
        writer.writerow(row)

2)读:

import csv
filename = 'example.csv'
with open(filename) as f:
    reader = csv.DictReader(f)
    for row in reader:
        # name是表第一行的某个数据,作为key
        name = row['name']
        print(name)

5.xml文件读写

1)写:

#coding=utf-8
# 生成xml文件
import xml.dom.minidom
def GenerateXml():
    impl = xml.dom.minidom.getDOMImplementation()

    dom = impl.createDocument(None, 'CONFIG_LIST', None)
    root = dom.documentElement

    employee = dom.createElement('COMP')
    root.appendChild(employee)

    nameE = dom.createElement('path')
    nameE.setAttribute("value", "aaaaaaaaaaa")  # 增加属性
    nameT = dom.createTextNode('linux')
    nameE.appendChild(nameT)
    employee.appendChild(nameE)

    f = open('config_new.xml', 'a')
    dom.writexml(f, addindent='  ', newl='\n')
    f.close()
GenerateXml()

2)读:

import xml.etree.cElementTree as ET

tree = ET.parse("config_new.xml")
root = tree.getroot()

COMP = root.findall('COMP')[0]#方法通过tag名字或xpath匹配第一层子元素
print("Tag:", COMP.tag, "Attributes:", COMP.attrib, "Text:", COMP.text.strip(), "Tail:", COMP.tail)

path = COMP.findall("path")[0]#方法通过tag名字或xpath匹配第一层子元素
print("Tag:", path.tag, "Attributes:", path.attrib, "Text:", path.text.strip(), "Tail:", path.tail)

#Element类和ElementTree类都有iter()方法可以递归遍历元素/树的所有子元素
for child in tree.iter(tag='path'): #tree是ElementTree对象
     print("Tag:", child.tag, "Attributes:", child.attrib, "Text:", child.text.strip())
上一篇 下一篇

猜你喜欢

热点阅读