一、利用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文件详细以及注意事项的更多相关文章

  1. python json格式和csv文件转换

    python json格式和csv文件转换 上代码 import csv import json ''' json格式示例 [{ "firstName":"Bill&qu ...

  2. Python爬虫小实践:寻找失踪人口,爬取失踪儿童信息并写成csv文件,方便存入数据库

    前两天有人私信我,让我爬这个网站,http://bbs.baobeihuijia.com/forum-191-1.html上的失踪儿童信息,准备根据失踪儿童的失踪时的地理位置来更好的寻找失踪儿童,这种 ...

  3. 总结day7 ---- 文件操作,读,写,追加,以及相关方法

    内容大纲 一:文件的基本操作, >常见问题 >encoding >绝对路径和相对路径的 二:文件的读写追加相关操作 >读(r, r+ ,rb,r+b) >写(w,w+,w ...

  4. Selenium爬取电影网页写成csv文件

    绪论 首先写这个文章的时候仅仅花了2个晚上(我是菜鸟所以很慢),自己之前略懂selenium,但是不是很懂csv,这次相当于练手了. 第一章 环境介绍 具体实验环境 系统 Windows10教育版 1 ...

  5. Python数据分析基础——读写CSV文件

    1.基础python代码: #!/usr/bin/env python3 # 可以使脚本在不同的操作系统之间具有可移植性 import sys # 导入python的内置sys模块,使得在命令行中向脚 ...

  6. python 下 excel,csv 文件的读写

    python 可以用利用xlrd 库读取数据excel数据,可以用xlwt写入excel数据,用csv 操作csv文件 xlrd xlwt  python 模块 官方链接  https://pypi. ...

  7. python读取和写入csv文件

    读取csv文件: def readCsv(): rows=[] with file(r'E:\py\py01\Data\system.csv','rb') as f: reads=csv.reader ...

  8. python 使用read_csv读取 CSV 文件时报错

    读取csv文件时报错 df = pd.read_csv('c:/Users/NUC/Desktop/成绩.csv' ) Traceback (most recent call last):  File ...

  9. python读取两个csv文件数据,进行查找匹配出现次数

    现有需求 表1 表2 需要拿表1中的编码去表2中的门票编码列匹配,统计出现的次数,由于表2编码列是区域间,而且列不是固定的,代码如下 #encoding:utf-8 ##导入两个CSV进行比对 imp ...

随机推荐

  1. opencv error: undefined reference to `png_set_expand_gray_1_2_4_to_8@PNG16_0'

    问题1:/usr/bin/ld: warning: libpng16.so.16, needed by /home/andrei/anaconda/lib/libopencv_highgui.so, ...

  2. [leetcode]Largest Rectangle in Histogram @ Python

    原题地址:https://oj.leetcode.com/problems/largest-rectangle-in-histogram/ 题意: Given n non-negative integ ...

  3. 如何使用Cassandra来存储time-series类型的数据

       Cassandra非常适合存储时序类型的数据,本文我们将使用一个气象站的例子,该气象站每分钟需要存储一条温度数据. 一.方案1,每个设备占用一行      这个方案的思路就是给每个数据源创建一行 ...

  4. 实录分享 | 计算未来轻沙龙:揭秘AutoML技术(视频 + PPT)

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/83542784 10 月 27 日 ...

  5. windows多线程同步--事件

    推荐参考博客:秒杀多线程第六篇 经典线程同步 事件Event   事件是内核对象,多用于线程间通信,可以跨进程同步 事件主要用到三个函数:CreateEvent,OpenEvent,SetEvent, ...

  6. ui-router 1.0 001 - resolve, component, sref-active

    特性介绍: state支持component形式 state的Resolve配置可以在激活state之前先获取数据, 绑定给component ui-sref-active="active& ...

  7. 常见网站CSS样式重置

    腾讯 1 2 3 4 5 6 7 8 9 body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea, ...

  8. Struct(二)

    struct2 权威指南 这一节通过一个详细的实例来讲解Struct2框架的应用 1 下载和安装Struts 2框架 (1) 登录http://struts.apache.org/download.c ...

  9. Windows 8系统默认开启的.Net Framework版本是4.0,而部分用户可能需要使用到3.5或以下版本,简单添加方法

    从网络途径下载的.Net Framework3.5是无法直接在Windows 8系统上安装的,我们可以通过Windows 8的添加功能来实现 1.打开控制面板,点击”启用或关闭Windows 功能“ ...

  10. 如何给Elasticsearch安装中文分词器IK

    安装Elasticsearch安装中文分词器IK的步骤: 1. 停止elasticsearch 2.2的服务 2. 在以下地址下载对应的elasticsearch-analysis-ik插件安装包(版 ...