如果不存在则创建文件,如果存在则不覆盖值

时间:2020-05-04 13:50:37

标签: python file overwrite

我想执行以下操作:

  1. 如果不存在则创建一个test.csv
  2. 在其中写入一些值(请参见代码)
  3. 将test.csv与data.csv合并并另存为test.csv
  4. 运行相同的脚本,但是文件名被更改/替换(从data.csv到data2.csv)
  5. 如果不存在则创建一个test.csv(现在存在)
  6. 在其中写入一些值(请参见代码),但不要覆盖数据中的当前值,只需添加它们即可。

这是我的代码:

    #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而不删除当前数据?

1 个答案:

答案 0 :(得分:1)

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)