總結了一下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編碼格式,防止中文亂碼