【发布时间】:2020-08-18 23:24:44
【问题描述】:
我想做以下事情:
- 如果不存在则创建一个 test.csv
- 在里面写一些值(见代码)
- 将 test.csv 与 data.csv 合并并另存为 test.csv
- 运行相同的脚本,但文件名已更改/替换(data.csv 到 data2.csv)
- 如果不存在则创建一个 test.csv(现在存在)
- 在其中写入一些值(见代码),但不要覆盖数据中的当前值,只需添加即可
这是我的代码:
#create a file if does not exist
import numpy as np
import pandas as pd
myseries=pd.Series(np.random.randn(5))
os.chdir(r"G:\..")
file = open('test.csv', 'a+')
df = pd.DataFrame(myseries, columns=['values'])
df.to_csv("test.csv" , index=False)
-----------------
# merge with data.csv
-------------
# create a file if does not exist, if exist write new values without overwritting the existing ones
myseries=pd.Series(np.random.randn(5))
os.chdir(r"G:\..")
file = open('test.csv', 'a+')
df = pd.DataFrame(myseries, columns=['values'])
df.to_csv("test.csv" , index=False)
# the values after merge were deleted and replaced with the new data
我尝试了 a、a+、w、w+,但文件中的当前数据已替换为新数据。 如何定义新数据写入 csv 而不删除当前数据?
【问题讨论】:
-
请说明
"a"为何不符合要求。 -
如果我们能运行你的代码就更好了。没有
os.chdir的例子可以由我们这些使用linux的人测试。 -
文件 test.csv 包含一列。现在我想添加另一列:
myseries=pd.Series(np.random.randn(5)) os.chdir(r"G:\...") file = open('test.csv', 'a') df = pd.DataFrame(myseries, columns=['values']) df.to_csv("test.csv" , index=False)但它只是在 test.csv 中写入新值,同时删除原始列 -
看看python3的pathlib,它提供
exists()和open()函数 -
添加新列意味着重写文件。