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

问题描述 投票:1回答:1

我想做以下工作。

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

python file overwrite
1个回答
1
投票

df.to_csv() 不关心文件打开的模式,使用的是 open() 并将覆盖该文件。相反,如果要在现有的csv文件末尾添加行,你可以使用 file.wite() 方法。

# 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)
© www.soinside.com 2019 - 2024. All rights reserved.