美文网首页
python-读写CSV文件以及合并

python-读写CSV文件以及合并

作者: 小二哥很二 | 来源:发表于2021-03-25 11:09 被阅读0次
    一、csv文件的多种读取

    1、标准库读取csv:结果把每一条数据生成列表,方便循环遍历

    import csv
    
    re = csv.reader(open('hospital_vehicle_team.csv'))
    for row in re:
        print(row)
    
    result:
    ['597', '2412372', '1605903']
    ['597', '2412375', '1605906']
    ['597', '2412378', '1605909']
    ['597', '2412381', '1605912']
    ['597', '2412384', '1605915']
    ['597', '2412387', '1605918']
    ['597', '2412390', '1605921']
    ['597', '2412393', '1605924']
    
    Process finished with exit code 0
    

    2、用pandas读取:用与展示带有维度的结果

    import pandas as pd
    
    data = pd.read_csv('hospital_vehicle_team.csv')
    print(data)
    
    result:
       597  2412372  1605903
    0  597  2412375  1605906
    1  597  2412378  1605909
    2  597  2412381  1605912
    3  597  2412384  1605915
    4  597  2412387  1605918
    5  597  2412390  1605921
    6  597  2412393  1605924
    
    二、csv文件的多种写入

    1、写入列表数据

    import csv
    
    headers = ['class','name','sex','height','year']
    
    rows = [
            [1,'xiaoming','male',168,23],
            [1,'xiaohong','female',162,22],
            [2,'xiaozhang','female',163,21],
            [2,'xiaoli','male',158,21]
        ]
    
    with open('learncsv.csv', 'w', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerow(headers)
        f_csv.writerows(rows)
    

    注意:如果写入的数据有空行,就需要加上参数newline=''
    2、写入字典数据

    NO.1写入嵌套列表嵌套字典
    import csv
    
    headers = ['class','name','sex','height','year']
    
    rows = [
            {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23},
            {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22},
            {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21},
            {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21},
        ]
    
    with open('learncsv.csv', 'w', newline='') as f:
        f_csv = csv.DictWriter(f, headers)
        f_csv.writeheader()
        f_csv.writerows(rows)
    
    Result
    NO.2写入单个字典数据
    import csv
    myDict = {'user1':'token1', 'user2':'token2', 'user3':'token3'}
    keyList = myDict.keys()
    valueList = myDict.values()
    # zip返回一个以元组为元素的列表
    rows = zip(keyList, valueList)
    with open('user.csv','w', newline='') as f:
        f_csv = csv.writer(f)
        for row in rows:
            f_csv.writerow(row)
    
    result:
    user1  token1
    user2  token2
    user3  token3
    
    三、读取txt文件内容写入csv文件

    - token.txt
    user1,token1
    user2,token2
    user3,token3

    import csv
    
    NO.1第一种写法:
    key = []
    value = []
    with open('token.txt') as f:
        data = f.readlines()
        # print(data)
        for content in data:
            key.append(content.split(',')[0])
            value.append(content.split(',')[1].strip())
    res = dict(zip(key, value))
    
    with open('token.csv', 'w', newline='') as f:
        f_csv = csv.writer(f)
        keylist = res.keys()
        valuelist = res.values()
        rows = zip(keylist,valuelist)
        for row in rows:
            f_csv.writerow(row)
        print('写入完毕!')
    
    
    NO.2第二种写法:
    res = []
    with open('user.txt')  as f:
        data = f.readlines()
        for i in data:
            org_list = i.strip().split(',')
            res.append(org_list)
    print(res)
    
    with open('ceshi.csv', 'w', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(res)     #切记一定是复数形式writerows
    

    - token.csv

    user1 token1
    user2 token2
    user3 token3

    相关文章

      网友评论

          本文标题:python-读写CSV文件以及合并

          本文链接:https://www.haomeiwen.com/subject/gzjlhltx.html