Python基础知识(十二)----- 文件读取处理

本文详细介绍了Python中如何处理文件,包括读取和写入CSV文件,解析JSON数据以及操作Excel表格。从基础的txt和csv格式到更复杂的json和excel,为Python文件操作提供全面的知识。
摘要由CSDN通过智能技术生成

一. csv文件读取处理

1. txt

def txt_writer():
    '''write file'''
    with open('data.txt','w',encoding='utf-8') as f:
        f.write('class')
        lines = [
            'address:Beijing\n',
            'qq:87657658\n',
            'website:http://uke.cc'
        ]
        f.writelines(lines)

def txt_read():
    '''read file'''
    with open('data.txt',encoding='utf-8') as f:
        for line in f:
            print(line,end='')

if __name__ == '__main__':
    #txt_writer()
    txt_read()

2. csv

  1. 读取csv
import csv
from collections import namedtuple

def csv_read():
    '''csv basic read'''
    with open('product.csv',encoding='utf8') as f:
        reader = csv.reader(f)
        headers = next(reader) #遍历第一行
        print(headers)
        for row in reader:
            print('order:{}\tproduct:{}\tprice:{}'.format(row[0],row[1],row[3]))

def csv_read_by_namedtuple():
    '''read csv and use namedtuple representing the name of column'''
    with open('product.csv',encoding='utf8') as f:
        reader = csv.reader(f)
        headers = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值