Python 读、写、追加csv文件详细以及注意事项
一、利用csv库创建文件
首先导入csv文件
import csv
根据指定的path创建文件:
def create_csv(path):
with open(path, "w+", newline='') as file:
csv_file = csv.writer(file)
head = ["name","sex"]
csv_file.writerow(head)
注意:open函数的参数newline的作用,处理csv读写时不同换行符 linux:\n windows:\r\n mac:\r
解释:
On input,if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
On output,if newline is None, any '\n' characters written are translated to the system default line separator,os.linesep. If newline is '', no translation takes place. If new line is any of the other legal values, any '\n' characters written are translated to the given string.
往文件中追加内容:
def append_csv(path):
with open(path, "a+", newline='') as file: # 处理csv读写时不同换行符 linux:\n windows:\r\n mac:\r
csv_file = csv.writer(file)
datas = [["hoojjack", "boy"], ["hoojjack1", "boy"]]
csv_file.writerows(datas)
读文件内容:
def read_csv(path):
with open(path,"r+") as file:
csv_file = csv.reader(file)
for data in csv_file:
print("data:", data)
测试:
def main():
path = "example.csv"
create_csv(path)
append_csv(path)
read_csv(path) if __name__ == "__main__":
main()
输出:
data: ['name', 'sex']
data: ['hoojjack', 'boy']
data: ['hoojjack1', 'boy']
二、利用pandas添加、读取文件
def pandas_write(path):
name = ["hoojjack", "hoojjack1"]
sex = ["boy", "boy"]
#字典中的key值即为csv中列名
data_frame = pd.DataFrame({"name":name, "sex":sex})
#将DataFrame存储为csv,index表示是否显示行名,default=True,path指写入的文件名称
data_frame.to_csv(path, index=True, sep='')
open函数读写参数说明:
w:以写方式打开,
a:以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+:以读写模式打开
w+:以读写模式打开 (参见 w )
a+:以读写模式打开 (参见 a )
rb:以二进制读模式打开
wb:以二进制写模式打开 (参见 w )
ab:以二进制追加模式打开 (参见 a )
rb+:以二进制读写模式打开 (参见 r+ )
wb+:以二进制读写模式打开 (参见 w+ )
ab+:以二进制读写模式打开 (参见 a+ )
Refernece:
[1] https://www.jianshu.com/p/0b0337df165a
[2] https://blog.csdn.net/lwgkzl/article/details/82147474
Python 读、写、追加csv文件详细以及注意事项的更多相关文章
- python json格式和csv文件转换
python json格式和csv文件转换 上代码 import csv import json ''' json格式示例 [{ "firstName":"Bill&qu ...
- Python爬虫小实践:寻找失踪人口,爬取失踪儿童信息并写成csv文件,方便存入数据库
前两天有人私信我,让我爬这个网站,http://bbs.baobeihuijia.com/forum-191-1.html上的失踪儿童信息,准备根据失踪儿童的失踪时的地理位置来更好的寻找失踪儿童,这种 ...
- 总结day7 ---- 文件操作,读,写,追加,以及相关方法
内容大纲 一:文件的基本操作, >常见问题 >encoding >绝对路径和相对路径的 二:文件的读写追加相关操作 >读(r, r+ ,rb,r+b) >写(w,w+,w ...
- Selenium爬取电影网页写成csv文件
绪论 首先写这个文章的时候仅仅花了2个晚上(我是菜鸟所以很慢),自己之前略懂selenium,但是不是很懂csv,这次相当于练手了. 第一章 环境介绍 具体实验环境 系统 Windows10教育版 1 ...
- Python数据分析基础——读写CSV文件
1.基础python代码: #!/usr/bin/env python3 # 可以使脚本在不同的操作系统之间具有可移植性 import sys # 导入python的内置sys模块,使得在命令行中向脚 ...
- python 下 excel,csv 文件的读写
python 可以用利用xlrd 库读取数据excel数据,可以用xlwt写入excel数据,用csv 操作csv文件 xlrd xlwt python 模块 官方链接 https://pypi. ...
- python读取和写入csv文件
读取csv文件: def readCsv(): rows=[] with file(r'E:\py\py01\Data\system.csv','rb') as f: reads=csv.reader ...
- python 使用read_csv读取 CSV 文件时报错
读取csv文件时报错 df = pd.read_csv('c:/Users/NUC/Desktop/成绩.csv' ) Traceback (most recent call last): File ...
- python读取两个csv文件数据,进行查找匹配出现次数
现有需求 表1 表2 需要拿表1中的编码去表2中的门票编码列匹配,统计出现的次数,由于表2编码列是区域间,而且列不是固定的,代码如下 #encoding:utf-8 ##导入两个CSV进行比对 imp ...
随机推荐
- 小程序快速部署富文本插件wxParser
为了解决html2wxml在ios下字体过大问题,又发现一个比较好用的富文本插件:wxParser. 目前 wxParser 支持对一般的富文本内容包括标题.字体大小.对齐和列表等进行解析.同时也支持 ...
- GraphQL入门2
将服务器端的代码升级了一下: var GraphQLSchema = require('graphql').GraphQLSchema; var GraphQLObjectType = require ...
- Linux编译步骤概述
Linux,一切皆文件! linux环境下,编译源码文件步骤总结 01.下载解压 一遍在开源网站有download/下载页面 02.安装基本编译环境 yum install -y gcc gcc-c+ ...
- arcgis server缓存路径修改
由于空间不够用,需要更换瓦片的输出路径,具体的修改方法如下: 1.打开ArcCatalog,打开GIS服务器,找到已经添加的gis服务器,一般都是机器名,如下所示,右键我的gis服务器(admin-t ...
- 9.5 翻译系列:数据注解之ForeignKey特性【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code ...
- Spark 论文篇-大型集群上的快速和通用数据处理架构(中英双语)
论文内容: 待整理 参考文献: An Architecture for Fast and General Data Processing on Large Clusters. Matei Zahari ...
- 转移 Visual Studio 2017 的安装临时文件
每次更新 Visual Studio 2017 会在 C 盘留下大量的缓存文件,因为目录比较深,怕以后忘了,用目录链接的形式转移到其它磁盘,也好方便清理: mklink /D C:\ProgramDa ...
- 物联网架构成长之路(14)-SpringBoot整合thymeleaf
使用thymeleaf作为模版进行测试 在pom.xml 增加依赖 <dependency> <groupId>org.springframework.boot</gro ...
- C#读取CSV
public class CSVFileHelper { /// <summary> /// 将DataTable中数据写入到CSV文件中 /// </summary> /// ...
- SSH免登录及原理
1.免登陆实现 1)在本机生成公钥/私钥对 ssh-keygen 执行成功后,在.ssh文件夹下,会多出两个文件 id_rsa和id_rsa.pub 2)将公钥写入远端服务器.ssh文件夹下的auth ...