文章目录
写在前面
读写方式 | 可否读写 | 文件不存在 |
---|---|---|
w | 覆盖写入 | 创建 |
w+ | 覆盖写入、可读 | 创建 |
r | 可读 | 报错 |
r+ | 覆盖写入、可读 | 报错 |
a | 附加写入 | 创建 |
a+ | 附加写入、可读 | 创建 |
excel
读
pandas
import pandas as pd
filename="try.xlsx"//文件路径
try_data=pd.read_excel(filename)
first way(遍历)
//遍历
data=[]
for i in try_data["data"]:
data.append(i)
second way(切片)
data=try_data.iloc[1:,0]//切片:[行数起始位置,列数]
openpyxl
import openpyxl
workbook = openpyxl.load_workbook('data.xlsx')
worksheet = workbook.get_sheet_by_name('Sheet1')
row1=[item.value for item in list(worksheet.rows)[0]]
print('第1行值',row1)
#第1行值 ['a',1]
col2=[item.value for item in list(worksheet.columns)[2]]
print('第2列值',col2)
#第2列值 [1,2,3]
cell_1_2=worksheet.cell(row=1,column=2).value
print('第1行第2列值',cell_1_2)
#第1行第2列值 1
max_row=worksheet.max_row
#3(即行数)
写
xlwt
xlwt不可以写为xlsx文件
import xlwt
g=[1,2,3]
book=xlwt.Workbook(encoding="utf-8",style_compression=0)//编码方式
sheet=book.add_sheet("sheet1",cell_overwrite_ok=True)//sheet名称及是否可写
#col={"money"}//列名称
for i in range(len(g)):
sheet.write(i,0,g[i])//write(列数,行数,数值)
savepath="temp.xls"//保存路径
book.save(savepath)
openpyxl
import openpyxl
wb=openpyxl.Workbook()
ws=wb.active
ws.append(pre_A2)
wb.save(pre_GDP_filename)
pandas
需要以字典形式
from pandas import *
data={'name':["a","b","c"],'age':[1,2,3]}
df=DataFrame(data)
df.to_excel("data.xlsx")
csv
读
first way
直接将csv转化成excel然后用上面的方法,一般来说直接改个后缀名就行。
second way
import csv
filename="try.csv"
with open(filename,"r",encoding="gbk") as f:
reader=csv.reader(f)
for row in reader:
print(row)
third way
import pandas as pd
data = pd.read_csv(filename, encoding="gbk")#data = pd.read_csv(filename, encoding="gbk", name=["a","b"],header=0)选用表头
写
import csv
filename="try.csv"
with open(filename,"a+",encoding="gbk",newline="") as f:
w=csv.writer(f)
w.writerow(row)
待更新,敬请期待……