python对txt,excel、CSV读读写

编程入门 行业动态 更新时间:2024-10-12 14:17:38

python对<a href=https://www.elefans.com/category/jswz/34/1769090.html style=txt,excel、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:#写入calibrationjson.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()

转载于:

更多推荐

python对txt,excel、CSV读读写

本文发布于:2024-03-12 21:35:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1732468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:txt   python   CSV   excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!