Python Notes12:数据读取

Python Notes12:数据读取

普通方法

  • 普通方法读取(open函数打开csv文件,然后使用for循环读取内容):
with open('D:\桌面\Data\水位数据\SW2-WL.csv') as f: for line in f: print(line) # .sec数据读取,📢📢📢数字需要多一个\转义 with open('D:\桌面\Data\水位数据\\2021-07-21.sec') as f: for line in f: print(line)
 
 
filename = 'D:\桌面\Data\水位数据\\2021-07-21.sec' # 读取指定行 with open(filename) as f: lines = f.readlines() last_line = lines[-1] print(last_line) f.close()
 

CSV标准库读取

import csv csv_reader = csv.reader(open("D:\桌面\Data\水位数据\SW2-WL.csv")) for row in csv_reader: print(row)

Pandas读取

  • 注意编码GBK、UTF-8
import pandas as pd # 读取csv # 方式一 data = pd.read_csv("D:\桌面\Data\水位数据\SW2-WL.csv",encoding="GBK") print(data) # 方式二 data = pd.read_table("D:\桌面\Data\水位数据\SW2-WL.csv",sep=",",encoding="GBK") print(data) # 读取.sec # 方式一 data = pd.read_csv("D:\桌面\Data\水位数据\\2021-07-21.sec",encoding="GBK") print(data) # # 方式二 data = pd.read_table("D:\桌面\Data\水位数据\\2021-07-21.sec",sep=",",encoding="GBK") print(data)