我想做以下事情:
- 如果 test.csv 不存在,则创建一个
- 在其中写入一些值(参见代码)
- 将 test.csv 与 data.csv 合并并另存为 test.csv
- 运行相同的脚本,但文件名已更改/替换(data.csv 为 data2.csv)
- 如果 test.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 而不删除当前数据?
最佳答案
df.to_csv()
不关心使用 open()
打开文件的模式,并且无论如何都会覆盖该文件。您可以使用 file.wite()
方法,而不是在现有 csv 文件的末尾追加行。
# For concatenation, remove the headers or they will show up as a row
contents = df.to_csv(index = False, header=False)
file = open("test.csv",'a')
file.write(contents)
file.close()
或者您可以读取、连接并重写文件
test = pd.read_csv('test.csv')
test = pd.concat([test, df])
test.to_csv('test.csv',index=False)
要追加列,您可以将轴设置为 1。
test = pd.read_csv('test.csv')
test = pd.concat([test, df], axis=1)
test.to_csv('test.csv',index=False)
关于python - 如果不存在则创建文件,如果存在则不覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61593858/