码迷,mamicode.com
首页 > 编程语言 > 详细

python对txt,excel、CSV读读写

时间:2019-03-14 21:21:00      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:mod   lse   exce   val   读取   数组   xls   with open   读写   

读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()

python对txt,excel、CSV读读写

标签:mod   lse   exce   val   读取   数组   xls   with open   读写   

原文地址:https://blog.51cto.com/14156081/2363227

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!