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 ...
随机推荐
- float:浮点型double:双精度实型decimal:数字型单精度浮点数(Single)双精度浮点数(double)
单精度浮点数(Single) 双精度浮点数(double) Decimal为SQL Server.MySql等数据库的一种数据类型,不属于浮点数类型,可以在定义时划定整数部分以及小 ...
- 序列化与反序列化的单例模式实现和readResolve()【转】
如: public class SingleTest implements Serializable{private static final long serialVersionUID = -860 ...
- [Mockito] Mock List interface
In this post, we are going to see more functionalities in Mockito. Mock a List interface: @Test publ ...
- virt-manager中为centos 7.2 扩容根分区
1. 打开virt-manager,添加一块磁盘. Add Hardware --> 选中Storage --> Manager (操作参考下图) 点击Manager之后,弹出Choose ...
- Java内省详解
内省和反射有什么区别: 反射式在运行状态把Java类中的各种成分映射成相应的Java类,可以动态的获取所有的属性以及动态调用任意一个方法,强调的是运行状态. 内省机制是通过反射来实现的,BeanIn ...
- 使用Nginx实现灰度发布(转)
灰度发布是指在黑与白之间,能够平滑过渡的一种发布方式.AB test就是一种灰度发布方式,让一部分用户继续用A,一部分用户开始用B,如果用户对B没有什么反对意见,那么逐步扩大范围,把所有用户都迁移到B ...
- 改变R和Matlab的默认工作目录
在快捷方式上右键->属性->起始位置处填上你需要的默认工作目录即可
- Java如何进行Base64的编码(Encode)与解码(Decode)?
https://blog.csdn.net/zhou_kapenter/article/details/62890262 *************************************** ...
- 【iCore4 双核心板_FPGA】例程一:GPIO输出实验——点亮LED
实验现象: 三色LED循环点亮. 核心源代码: module led_ctrl( input clk_25m, input rst_n, output fpga_ledr, output fpga_l ...
- Angularjs中config中置入以下拦截器
$httpProvider.interceptors.push(['$rootScope', '$q', '$localStorage', function ($rootScope, $q, $loc ...