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

756-周同学

发表文章数:47

热门标签

,
首页 » Python » 正文

一. 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 = next(reader)
        Row = namedtuple('Row',headers) #申明一个类
        for r in reader:
            row = Row(*r)
            print('{} -> {} -> {}'.format(row.ProductID,row.ProductName,row.UnitPrice))

def csv_read_by_dict():
    '''read csv to dict'''
    with open('product.csv',encoding='utf8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            print('{} -> {} -> {}'.format(row['ProductID'],row.get('ProductName','not fill'),row.get('UnitPrice','0.0')))

if __name__ == '__main__':
    csv_read()
    csv_read_by_namedtuple()
    csv_read_by_dict()
  1. 写csv
import csv

def csv_reader():
    with open('mycourse.csv',encoding='utf8') as f:
        reader = csv.reader(f)
        headers = next(reader)
        print(headers)
        for row in reader:
            print(row)

def csv_write():
    '''write csv file'''
    headers = ['ID','name','teacher']
    rows = [
        (1,'Python','Eason'),
        (2, 'C#', 'Eason'),
        (3, 'Django', 'Eason'),
        (4, '.NET', 'Eason')
    ]
    with open('mycourse.csv','w',encoding='utf8',newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)

def csv_writer_dict():
    '''write in dict way'''
    headers = ['ID','Title','Org','Url']
    rows = [
        {'ID':1,'Title':'Python','Org':'Class','Url':'http://uke.cc'},
        {'ID': 2, 'Title': 'Python', 'Org': 'Class', 'Url': 'http://uke.cc'},
        {'ID': 3, 'Title': 'Python', 'Org': 'Class', 'Url': 'http://uke.cc'},
        {'ID': 4, 'Title': 'Python', 'Org': 'Class', 'Url': 'http://uke.cc'},
        dict(ID=5,Title='C#',Org='Class',Url='http://uke.cc')
    ]
    with open('mycourse2.csv','w',encoding='utf8',newline='') as f:
        writer = csv.DictWriter(f, headers)
        writer.writeheader()
        writer.writerows(rows)

if __name__ == '__main__':
    #csv_write()
    #csv_reader()
    csv_writer_dict()

二. Json

import json

def json_basic():
    data = {
        'ID':1,
        'Course':'Python',
        'Org':'Class',
        'Price':98.00,
        'Website':'http://codr.com'
    }
    print('inital data')
    print(data)
    json_str = json.dumps(data) ##变为字符串
    print(json_str)
    json_data = json.loads(json_str) #还原字符串
    print(json_data)

def json_writer_file():
    '''write json file'''
    data = {
        'ID': 1,
        'Course': 'Python',
        'Org': 'Class',
        'Price': 98.00,
        'Website': 'http://codr.com'
    }
    with open('data.json','w',encoding='utf8') as f:
        json.dump(data,f)

def json_read_file():
    '''read json file'''
    with open('data.json',encoding='utf8') as f:
        data = json.load(f)
        print(data)

def json_type_diff():
    '''type difference'''
    data = {
        'Discontinued':False,
        'Title':'iPhone7s',
        'Category':None,
        'Price':5999.00
    }
    print(json.dumps(data))

if __name__ == '__main__':
    #json_basic()
    #json_writer_file()
    #json_read_file()
    json_type_diff()

三. Excel文件读取

import xlrd

def xl_read():
    '''excel read'''
    book = xlrd.open_workbook('product.xls') #open a book
    for sheet in book.sheets():
        print(sheet.name)
        
def xl_read_data():
    '''read data'''
    book = xlrd.open_workbook('product.xls')
    sheet = book.sheet_by_name('Product')
    print('book:{}'.format(sheet.name))
    print('data rows:{}'.format(sheet.nrows))
    print('product data')
    print('='*50)
    for i in range(sheet.nrows):
        print(sheet.row_values(i)) #获取索引指定的数据行

if __name__ == '__main__':
    #xl_read()
    xl_read_data()
标签:

未经允许不得转载:作者:756-周同学, 转载或复制请以 超链接形式 并注明出处 拜师资源博客
原文地址:《Python基础知识(十二)—– 文件读取处理》 发布于2020-04-12

分享到:
赞(0) 打赏

评论 抢沙发

评论前必须登录!

  注册



长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

Vieu3.3主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录