如何写入表

时间:2017-09-22 21:52:02

标签: python python-3.x csv

这是我在Python中的代码:

with open('my.csv', 'a', newline='') as fp:
writer = csv.writer(fp, delimiter=',')
writer.writerow(('Users','Date','Location'))
 for row in my_dict.items():
     writer.writerow(row)

我的CSV输出如下:

当前表的截图

那么,我如何获得CSV格式如下截图:

想要的表格的截图

任何帮助都会表示赞赏。

2 个答案:

答案 0 :(得分:2)

user = ""
with open('my.csv', 'a', newline='') as fp:
    writer = csv.writer(fp, delimiter=',')
    writer.writerow(('Users','Date','Location'))
    for date, location in my_dict.items():
        writer.writerow(user, date, location)

答案 1 :(得分:1)

这是一种使用pandas库的方法:

import pandas as pd
import numpy as np
import io

csv = """
Users,Date,Location
23-sep,Guatemala-Guatemala,"""

df = pd.read_csv(io.StringIO(csv))

df.columns = np.roll(df.columns,-1) #shift columns
df = df[np.roll(df.columns,1)] # use previous order

df.to_csv("output.csv",index=False)

或者使用文件:

import pandas as pd
import numpy as np
import io

df = pd.read_csv("input.csv")

df.columns = np.roll(df.columns,-1) #shift columns
df = df[np.roll(df.columns,1)] # use previous order

df.to_csv("output.csv",index=False)