一、利用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. iframe实现Ajax文件上传效果示例

    <!doctype html> <html> <head> <meta charset=utf-8> <head> <title> ...

  2. EditText控件设置只读

    android的文本框输入控件(EditText),有时需要设置控件为只读,最简单的方法就是在layout xml文件中设置EditText的android:editable属性值为false即可,但 ...

  3. Django中使用Celery,定制应用程序中定义的shared_task未在定期任务管理页面的注册任务中显示

    解决办法: 在项目 proj/proj/celery.py文件中,看到下面这行配置: celery_app.config_from_object('django.conf:settings', nam ...

  4. ASP.NET MVC 一款可预览、裁剪头像上传组件

    今天介绍一款Web上常用的头像上传组件,常用于头像上传时对用户上传的图片进行裁剪并实时预览,最终效果如下: 源代码结构: Github地址: https://github.com/FrankFan/A ...

  5. 阿里云centos安装docker-engine实践

    近日在阿里云ECS服务器(centos系统)中安装docker,参考官方指南 https://docs.docker.com/engine/installation/linux/centos/  大概 ...

  6. 9.11 翻译系列:数据注解特性之--Timestamp【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/TimeStamp-dataannotations-attribute-in-code- ...

  7. elasticsearch 忽略大小写模糊搜索实现(转)

    在es查询时不区分大小写,可以让查询更方便,具体设置如下: { "settings": { "analysis": { "analyzer" ...

  8. Java Web开发基础零星知识

    1. Web的三个核心标准 万维网的核心标准有三个,分别是URL.HTTP和HTML. URL(统一资源定位符,Universal Resource Locator),为描述Internet上的网页以 ...

  9. LeetCode OJ 238. Product of Array Except Self 解题报告

        题目链接:https://leetcode.com/problems/product-of-array-except-self/ 238. Product of Array Except Se ...

  10. 透彻理解Spring事务设计思想之手写实现

    前言 事务,是描述一组操作的抽象,比如对数据库的一组操作,要么全部成功,要么全部失败.事务具有4个特性:Atomicity(原子性),Consistency(一致性),Isolation(隔离性),D ...