python逐行写入csv_python对txt,excel、CSV读读写

读txt

file_obj=open("1.txt","rb")#mode=r/w

txt=file_obj.read()//一次全部读取,基本能cover

txt=file_obj.readline()//逐行读取,带有/R/N

txt=file_obj.readline()//逐行读取下一行,带有/R/N

txt=file_obj.readlines()//读取为一个数组

file_obj.close()

写txt

file_obj=open("1.txt","w")#mode=r/w

txt="123456\n"//靠\n换行

file_obj.write(txt)

file_obj.writelines(txt)

file_obj.writelines([txt,txt])

file_obj.close

用with的方法

with open("1.txt","r",encoding="utf-8") as file_obj:

a=file_obj.read()

print(a)

从json读取

json.load()//从文件中读取

json.loads()//从字符串读取

json.dump()//向文件写入

json.dumps()//向字符串写入

import json

Dict1={

"d":-0.5000000000000000,

"e":0.10000000000,

"f":{

"ST/X":[-153,21.3],

"WERT":[0.03650,0.0360,0.02629]

}

}

Dict2={

"a":-0.5000000000000000,

"b":0.300450000000000000,

"c":{

"ST/X":[-150.0,85.6,221.3],

"WERT":[0.03650,0.0360,0.02629]

}

}

dict3={}

dict3.update(Dict1)

dict3.update(Dict2)

with open("1.json","w") as f:#写入calibration

json.dump(dict3,f)

读写csv

import pandas as pd

file_obj="1.csv"

file_obj2="2.csv"

a=pd.read_csv(file_obj)

print(a)

a.to_csv(file_obj2)

读写Excel

import pandas as pd

df_obj=pd.read_excel("1.xlsx",sheetname="Sheet1")#读取一个表

print(df_obj)#预览前几行

df_objs=pd.read_excel("1.xlsx",sheetname=["Sheet1","Sheet2","Sheet3"])#读取多个表,存字典中

for j in df_objs.values():

print(j)

import pandas as pd

df_obj=pd.read_excel("1.xlsx",sheetname="Sheet1")

print(df_obj)#预览前几行

# df_obj.to_excel("2.xlsx",index=False)

writer=pd.ExcelWriter("2.xlsx")

df_obj.to_excel(writer,"1")

df_obj.to_excel(writer,"21")

df_obj.to_excel(writer,"Sheet3")

writer.save()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值