美文网首页
python3读/写文件,读csv

python3读/写文件,读csv

作者: 杜艳_66c4 | 来源:发表于2019-05-17 16:23 被阅读0次

    用Python 内构函数open来写入字符串到txt文件里

    text = 'now ,we\'re  write into the file'
    '''
    调用buid-in函数,open打开或创建文件
    如果file不存在,就自动创建,w 写的模式,r读的模式
    '''
    
    file = open(r'E:\toolsd\pythoncode\example.txt','w')
    file.write(text)
    file.close()
    readtxt = open('example.txt','r').read()
    
    print(readtxt)
    '''
    file = open(r'E:\toolsd\pythoncode\example.txt','w')指定了文件的路径,
    若直接 file = open('example.txt','w'),则文件在当前的.py文件下
    文件路径前面的 ‘r’ 表示不需要转义,原义输出,因为上面有\,反斜杠默认是转义,所以需要添加r
    输出效果
    '''
    

    读csv,逗号分隔符
    主要有read和write两个功能
    1、先创建一个csv文件,直接将txt的后缀改为csv即可。例如数据如下

    "Year", "Country","Sex","Name"
    "2001","China","Male","Bob"
    "2002","UK","F","Bonny"
    "2003","US","M","王军"
    "2004","South Korea","M","Tom"
    "2005","Japan","F","Alicia"
    "2019","Germany","M","Robbin"
    

    2、csv文件直接放在当前.py的路径下面

    3、demo.py

    import csv
    
    with open('example.csv','r') as csvfile:
        readCSV = csv.reader(csvfile)
        for row in readCSV:
            print(row)
    

    结果:

    image.png 4、进入到指定的某列
    import csv
    
    with open('example.csv','r') as csvfile:
        readCSV = csv.reader(csvfile)
        for row in readCSV:
            #print(row)
            print(row[0])
           # print(row[1],row[0])
    

    结果:

    image.png 5、单独输出每列
    import csv
    with open('example.csv','r') as csvfile:
        readCSV = csv.reader(csvfile)
        years =[]
        countys =[]
        sexs = []
        for row in readCSV:
            year = row[0]
            county = row[1]
            sex = row[2]
    
            years.append(year)
            countys.append(county)
            sexs.append(sex)
        print(years)
        print(countys)
        print(sexs)
    
    结果: image.png

    相关文章

      网友评论

          本文标题:python3读/写文件,读csv

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