总结了一下R、python、MySQL常用的文件读写操作(其中,R和python中为了使读写操作更加方便,都需要先指定工作路径)
R
指定工作路径:setwd('file_path')
- 数据写入
csv文件写入:
data=read.csv('xxx.csv',header=T,sep=',',skip=..)
txt文件写入:
data=read.table('xxx.txt',header=T,sep=',')
scan(file='xxx.txt',what='',skip=..,sep='')
**scan用于读入纯字符或数字(b不能读入混合类型的数据)且读入没有表头
剪贴板数据写入:
data=read.table('clipboard',header=..,sep=',')
header:是否读入表头(T or F)
sep:分隔符类型,默认为空格或Tab,也可自定义为逗号分隔符等
skip:读取时跳过的行数
what:给出数据读取的类型和精度,如integer(0),numeric(0)
- 数据写出
write.table(data,'data.txt',append=FALSE,quote=TRUE,sep=',')
write.csv(data,'data.csv',append=FALSE,quote=TRUE,sep=',')
python
指定工作路径:
import os
os.chdir('file_path')
- 数据写入:
txt文件写入:
data=open('file.txt','r',encoding='utf-8').read()
data=open('file.txt','r',encoding='utf-8').readlines()
read一次性读入全部数据
readlines读取文件所有行,并且保存在一个列表中,每一行作为一个元素
csv,xls文件写入:
data=pd.read_excel('xx.xls',header=None,encoding='utf-8')
data=pd.read_csv('xx.csv',header=None,encoding='utf-8')
- 数据写出:
整个文件写出:
data.to_csv('file_path',encoding='ANSI')
按行写出操作(通常和for循环搭配使用!):
##csv文件写出
import xlwt
workbook=xlwt.Workbook(encoding='utf-8')
worksheet=workbook.add_sheet('') #添加sheet
worksheet.write(0,0,item1) #在表格0行0列写入item1,以此类推
worksheet.write(0,1,item2).....
workbook.save('xxx.csv')
#csv库
import csv
csv_file=open('data.csv')
csv_writer=csv.writer(csv_file,delimiter=',',lineterminator='\n')#delimiter按逗号分隔,lineterminator='\n'使得行与行之间不留空行
csv_writer.writerow([item1,item2,item3,...])
csv_file.close()
##txt文件按行写出
with open('xxx.txt','w') as f:
f.write(line)
MySQL
mysql中读写文件稍微复杂一点,需要修改一下my.ini配置文件
- 数据写入
首先,需要在[mysqld]和[mysql]下添加命令local-infile=1
,否则会报错
写出命令如下:
load data local infile 'file_path' into table t_name fields terminated by ',' ignore 1 lines;
file_path:文件存储路径
t_name:数据表名
fields terminated by ‘,’ :以逗号进行分隔
ignore 1 lines :跳过第一行字段名
- 数据写出
同样,首先需要在[mysqld]下添加命令secure_file_priv='file_path'
写出命令如下:
select ... from table_name into outfile 'file_path/data.csv' character set gbk fields terminated by ','
table_name:数据表名
character set gbk:设置gbk编码格式,防止中文乱码