1. 程式人生 > >python對txt,excel、CSV讀讀寫

python對txt,excel、CSV讀讀寫

csv enc als pri 一個數 and ict date json讀取

讀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讀讀寫