Python操作csv修改内容并保存
Python操作csv修改内容及保存导出
·
目的:修改csv某列数据格式及内容,最后再保存输出csv
python实现代码如下
import csv
import datetime
import pandas as pd
if __name__ == '__main__':
## 文件路径
csv_path = './data/ganglia-metrics.csv'
## 导出文件命名
new_csv_name = "new_ganglia-metrics.csv"
## 读取csv信息
data = pd.read_csv(csv_path)
## 我就只有两列数据,就定义了两个数组,处理完存放再数组里,最后再保存输出
timestampList = []
cpu_idleList = []
# 修改csv某列数据信息
for i in range(data.shape[0]):
# 修改格式
t = (datetime.datetime.strptime(data.loc[i]['Timestamp'], "%Y-%m-%dT%H:%M:%S+00:00") + datetime.timedelta(
hours=2)).strftime("%Y-%m-%d %H-%M-%S")
# 写入数组
timestampList.append(t)
cpu_idleList.append(data['cpuIdle'][i])
# 写出到csv
with open(new_csv_name, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
# 先写入columns_name
writer.writerow(["Timestamp", "cpuIdle"])
for i in range(len(timestampList)):
writer.writerow([timestampList[i], cpu_idleList[i]])
更多推荐
已为社区贡献1条内容
所有评论(0)