python对txt,excelCSV读读写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python对txt,excelCSV读读写相关的知识,希望对你有一定的参考价值。

读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
"//靠
换行
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,excelCSV读读写的主要内容,如果未能解决你的问题,请参考以下文章

Python文件读写

Python txt读写(待)

python实现读写txt文件

python读写文件

python txt文件常用读写操作

python中open函数的用法