python写入csv文件的几种方法总结

最常用的一种方法,利用pandas包

import pandas as pd

#任意的多组列表
a = [1,2,3]
b = [4,5,6]    

#字典中的key值即为csv中列名
dataframe = pd.DataFrame({‘a_name‘:a,‘b_name‘:b})

#将DataFrame存储为csv,index表示是否显示行名,default=True
dataframe.to_csv("test.csv",index=False,sep=‘,‘)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
   a_name  b_name
0       1       4
1       2       5
2       3       6
  • 1
  • 2
  • 3
  • 4

同样pandas也提供简单的读csv方法

import pandas as pd
data = pd.read_csv(‘test.csv‘)
  • 1
  • 2

会得到一个DataFrame类型的data,不熟悉处理方法可以参考pandas十分钟入门



另一种方法用csv包,一行一行写入

import csv

#python2可以用file替代open
with open("test.csv","w") as csvfile:
    writer = csv.writer(csvfile)

    #先写入columns_name
    writer.writerow(["index","a_name","b_name"])
    #写入多行用writerows
    writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
index   a_name  b_name
0       1       3
1       2       3
2       3       4
  • 1
  • 2
  • 3
  • 4

读取csv文件用reader

import csv
with open("test.csv","r") as csvfile:
    reader = csv.reader(csvfile)
    #这里不需要readlines
    for line in reader:
        print line

原文地址:https://www.cnblogs.com/zlel/p/9195826.html

时间: 2024-08-27 00:29:21

python写入csv文件的几种方法总结的相关文章

python写入csv文件中文乱码解决方案

今天修改程序,需要写入csv文件,发现中文会乱码,后来查了下,可以设置文件写入属性后,就可以解决: import csvimport codecslist=['a101','b101']sumlist=[]for str in list: templist=[] templist.append('a') templist.append('b') templist.append('c') sumlist.append(templist)csvfile = file('csv_test.csv',

python 逐行读取文件的几种方法

Python四种逐行读取文件内容的方法 下面四种Python逐行读取文件内容的方法, 分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可. 方法一:readline函数 # -*- coding: UTF-8 -*- f = open("/pythontab/code.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: # pri

python 写入csv文件

import csv fieldnames = ['Column1', 'Column2', 'Column3', 'Column4'] rows = [{'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'}, {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'}, {'Column1': '0', 'Column2': '1', 'Column3

python写入csv文件多一行

如执行下面的代码: 1 import csv 2 3 if __name__ == "__main__": 4 5 content1 = ['hello'] 6 content2 = ['world'] 7 8 with open('test.csv', 'w') as f: 9 writer = csv.writer(f) 10 writer.writerow(content1) 11 writer.writerow(content2) 打开test.csv文件查看,如下图: 可以看

MySQL将查询结果写入到文件的2种方法

1.SELECT INTO OUTFIL: 这种方法不能覆盖或者追加到已经存在的文件,只能写入到新文件,并且建立文件的路径需要mysql进程用户有权限建立新文件. mysql 61571 60876 15 Aug27 ? 3-10:58:08 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/data/mysqldata/data --plugin-dir=/usr/local/mysql/lib/plugin -

python 逐行读取文件的三种方法

方法一: 复制代码代码如下: f = open("foo.txt")             # 返回一个文件对象  line = f.readline()             # 调用文件的 readline()方法  while line:      print line,                 # 后面跟 ',' 将忽略换行符      # print(line, end = '') # 在 Python 3中使用      line = f.readline()

python 爬虫保存文件的几种方法

import os os.makedirs('./img/', exist_ok=True) IMAGE_URL = "https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png" def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './img/image1.png')

python读取和写入csv文件

----------------python读取csv文件------------------ #导入csv 创建一个csv文件,输入内容 import csv #1.找到需要被打开的文件路径,通过open打开文件,声明打开的方式,声明编码格式 csv_file=open(r'csv文件路径', mode='r', encoding='utf-8') #2.通过csv模组提供的读取方法来读取打开的文件 csv_data=csv.reader(csv_file) #3.通过for循环遍历读取数据存

Python复制文件的九种方法

以下是演示"如何在Python中复制文件"的九种方法. shutil copyfile()方法 shutil copy()方法 shutil copyfileobj()方法 shutil copy2()方法 os popen方法 os系统()方法 Thread()方法 子进程调用()方法 子进程check_output()方法 1. Shutil Copyfile()方法 该方法只有在目标可写时才将源的内容复制到目的地.如果您没有写入权限,则会引发IOError. 它通过打开输入文件进