python操作csv文件

一、参考链接

https://docs.python.org/zh-cn/3/library/csv.html?highlight=csv#module-csv

二、写入csv文件

1、方式一

   def test_write(self):
        with open('./data.csv','w',encoding='utf-8') as f:
            cw= csv.writer(f)
            cw.writerow(['test','csv','demo'])

python操作csv文件

2、方式二

  def test_dict_writer(self):
        '''
        参数newline是用来控制文本模式之下,一行的结束字符。可以是None,’’,\n,\r,\r\n等。
        不加写入的则为如下格式:
                    username,password

                    xian1,test1234

                    xian2,test1234

                    xian3,test1234
        :return:
        '''
        with open('./data.csv','w',encoding='utf-8',newline='') as f:
            filesnames=['username','password']
            cw=csv.DictWriter(f,fieldnames=filesnames)
            cw.writeheader()
            cw.writerow({'username':'xian1','password':'test1234'})
            cw.writerow({'username':'xian2','password':'test1234'})
            cw.writerow({'username':'xian3','password':'test1234'})

python操作csv文件

三、读取csv文件

data.csv文件如下:

username,password
xian1,test1234
xian2,test1234
xian3,test1234

1、方式一

  def test_read(self):
        with open('./data.csv','r',encoding='utf-8') as f:
            cr=csv.reader(f)
            for row in cr:
                print(row)

python操作csv文件
2、方式二

  def test_dict_reader(self):
        with open('./data.csv','r',encoding='utf-8') as f:
            cr=csv.DictReader(f)
            for row in cr:
                print(row['username'],row['password'])

python操作csv文件

上一篇:Redhat 7.2 编译安装PostgreSQL 10


下一篇:安装MySQL