Python之文件读写(csv文件,CSV库,Pandas库)
前言
一.Python文件读取
1. open函数是内置函数之with操作
- 关于路径设置的问题斜杠设置成D:\\文件夹\\文件或是D:/文件夹/文件
f = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- file: 必需,文件路径(相对或者绝对路径)。
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener:
打开文件之后就要开始操作了,一个读取了,但是要是没有打开文件就会报错,或则在读取的过程中报错就不会关闭文件了,所以为了无论报错与否,在使用完文件后就要关闭文件。如下:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
这样写太过于麻烦,Python中直接使用with来直接自动来帮我们调用close()
with open('/path/to/file', 'r') as f:
print(f.read())
上面的写法和try...finally效果一样。
2. 读文件
f.read()一次性读入所有数据,保险起见可以规定每次读取的数据大小,f.read(size)进行反复调用读取。
f.readline(),每次读取一行,f.readlines()一次读取多行另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉
3. 写文件
和写文件一样,首先使用open函数直接打开但是传入标识符mode='w'即写入模式。
可以调用f.write()写入内容,写完之后务必使用f.close()关闭文件。
方法一:
f = open('/Users/michael/test.txt', 'w')
f.write('Hello, world!')
f.close()
方法二:
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')
- 要写入或则是读取特定编码的文本文件,请给open()函数传入encoding参数,将字符串自动转换成指定编码。
4. 多个文件的读写操作
方法一:
with open('/home/xbwang/Desktop/output_measures.txt','r') as f:
with open('/home/xbwang/Desktop/output_measures2.txt','r') as f1:
with open('/home/xbwang/Desktop/output_output_bk.txt','r') as f2:
........
........
........
方法二:
with open('/home/xbwang/Desktop/output_measures.txt','r') as f:
........
with open('/home/xbwang/Desktop/output_measures2.txt','r') as f1:
........
with open('/home/xbwang/Desktop/output_output_bk.txt','r') as f2:
........
二、读取CSV文件
1. 使用csv库进行读写操作
1.获取csv文件的文件表头
#方式一
import csv
with open("D:\\test.csv") as f:
reader = csv.reader(f)
rows=[row for row in reader]
print(rows[0])
#方式二
import csv
with open("D:\\test.csv") as f:
#1.创建阅读器对象
reader = csv.reader(f)
#2.读取文件第一行数据
head_row=next(reader)
print(head_row)
2.读取文件的某一列数据
说明使用csv.reader()返回一个reader对象,它将迭代给定csvfile中的行。
csvfile可以是任何支持迭代器协议的对象,
并在每次__next__()调用其方法时返回一个字符串- 文件对象和列表对象都是合适的。
import csv
with open("D:\\test.csv") as f:
reader = csv.reader(f)
column=[row[0] for row in reader]
print(column)
3.写入csv文件
import csv
with open("D:\\test.csv",'a') as f:
row=['曹操','23','学生','黑龙江','5000']
write=csv.writer(f)
write.writerow(row)
print("写入完毕!")
- writerow()方法是一行一行写入,
- writerows方法是一次写入多行
2. 使用pandas库进行csv文件操作
1.读取csv的全部文件
import pandas as pd
path= 'D:\\test.csv'
with open(path) as file:
data=pd.read_csv(file)
print(data)
2.读取文件前几行数据
import pandas as pd
path= 'D:\\test.csv'
with open(path)as file:
data=pd.read_csv(file)
#读取前2行数据
head_datas = data.head(0)
head_datas = data.head(1)
print(head_datas)
说明head函数就是用来读取哪一行的
3.读取文件哪一行的全部内容
import pandas as pd
path= 'D:\\test.csv'
with open(path)as file:
data=pd.read_csv(file)
#读取第一行所有数据
print(data.ix[0,])
4.读取文件的哪几行数据
import pandas as pd
path= 'D:\\test.csv'
with open(path)as file:
data=pd.read_csv(file)
#读取第一行、第二行、第四行的所有数据
print(data.ix[[0,1,3],:])
5.读取所有行和列数据
import pandas as pd
path= 'D:\\test.csv'
with open(path)as file:
data=pd.read_csv(file)
#读取所有行和列数据
print(data.ix[:,:])
Python之文件读写(csv文件,CSV库,Pandas库)的更多相关文章
- Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- 【转发】Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- Python 用configparser读写ini文件
一.configparser 简介Python用于读写ini文件的一个官方标准库.具体详见官网链接 二.configparser 部分方法介绍 方法 描述 read(filenames) filesn ...
- python xlrd,xlwt 读写excel文件
python 读excel文件,需要xlrd库.下载地址:https://pypi.python.org/pypi/xlrd python 写excel文件,需要xlwt库.下载地址:https:// ...
- python第二十九课——文件读写(复制文件)
自定义函数:实现文件复制操作有形参(2个) 没有返回值相似版(不用) def copyFile(src,dest): #1.打开两个文件:1个关联读操作,1个关联写操作 fr=open(src,'rb ...
- python学习之文件读写入门(文件读的几种方式比较)
1.文件读写简单实例:(以w写的方式打开一个文件,以r读一个文件) # Author : xiajinqi # 文件读写的几种方式 # 文件读写 f = open("D://test.txt ...
- 12--Python入门--文件读写--TXT文件
在进行数据分析之前,可能需要读写自己的数据文件.或者在完成数据分析之后,想把结果输出到外部的文件在Python中,利用pandas模块中的几个函数,可以轻松实现这些功能,利用pandas读取文件之后数 ...
- Linux Direct 文件读写(文件DIO)
有时候,读写文件并不想要使用系统缓存(page cache),此时 direct 文件读写就派上了用场,使用方法: (1)打开文件时,添加O_DIRECT参数: 需要定义_GNU_SOURCE,否则找 ...
- 文件操作ofstream,open,close,ifstream,fin,依照行来读取数据, fstream,iosin iosout,fio.seekg(),文件写入和文件读写,文件拷贝和文件
1.ofstream,open,close 写入文件 #include<iostream> #include<fstream> using namespace std; ...
- QT_8_Qt中的事件处理_定时器事件_定时器类_事件分发器_事件过滤器_绘图事件_高级绘图事件_绘图设备_QFile 文件读写_QFileInfo文件信息
Qt中的事件处理 1.1. 捕获QLabel中是鼠标事件 1.2. enterevent 鼠标进入 1.3. leaveevent 鼠标离开 1.4. 鼠标按下MyLabel::mousePressE ...
随机推荐
- 阿里云RDS数据库备份同步到自建库方法(SHELL脚本)
一.背景: 由于阿里云RDS生产库每天都需要备份且拷贝到自建读库,而如果使用阿里云的自动拷贝到只读实例, 费用太高, 故采用自编写同步脚本方法实现. 二.前提: 1). 已开通阿里云RDS, 且开启定 ...
- select2的简单使用
静态下拉列表 修改 type_template.html 引入JS <!-- slect2插件--> <link rel="stylesheet" href=& ...
- Spring Boot入门及第一个案例
一:SpringBoot是什么 springboot是对spring的缺点进行改善和优化,约定大于配置 开箱即用 没有代码生成 也无需xml 文件配置 可以修改属性值来满足需求 1) Spri ...
- windows 下验证文件MD5
CertUtil -hashfile C:\Users\admin\Downloads\aaa.txt MD5 CertUtil -hashfile C:\Users\admin\Downloads\ ...
- 【翻译】asp.net core 3.0基本概念
这篇文章描述了开发asp.net core所需要掌握的基本概念. 原文地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?vie ...
- nginx fastcgi模块ngx_http_fastcgi_module详细解析、使用手册、完整翻译
ngx_http_fastcgi_module 模块允许将请求传递给 FastCGI 服务器. 示例配置 location / { fastcgi_pass localhost:9000; fastc ...
- 华为 鸿蒙系统(HarmonyOS)
HarmonyOS Ⅰ. 鸿蒙系统简介 鸿蒙系统(HarmonyOS),是第一款基于微内核的全场景分布式OS,是华为自主研发的操作系统.2019年8月9日,鸿蒙系统在华为开发者大会<HDC.20 ...
- 洛谷 p1387最大正方形
洛谷 p1387最大正方形 题目描述 在一个n*m的只包含0和1的矩阵里找出一个不包含0的最大正方形,输出边长. 输入格式 输入文件第一行为两个整数n,m(1<=n,m<=100),接下来 ...
- zsh禁用自动更新
编辑.oh-my-zsh/oh-my-zsh.sh文件 set DISABLE_AUTO_UPDATE = false # Check for updates on initial load... i ...
- 为python脚本增加命令行参数
from argparse import ArgumentParser p = ArgumentParser() p.add_argument('-b', '--body', help='Return ...