【问题标题】:create a file if does not exist, if exist do not overwrite the values如果不存在则创建文件,如果存在则不覆盖值
【发布时间】:2020-08-18 23:24:44
【问题描述】:

我想做以下事情:

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

【问题讨论】:

  • 请说明"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()函数
  • 添加新列意味着重写文件。

标签: python file overwrite


【解决方案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)

【讨论】:

  • df.to_csv() 不带文件名返回要写入的字符串
  • myseries=pd.Series(np.random.randn(5)) os.chdir(r"G:\..") file = open('test.csv', 'a') df = pd.DataFrame(myseries, columns=['values']) contents = df.to_csv(index = False, header=False) file.write(contents) file.close() 你能说得更具体点吗?这个我试过了,但它保持原始数据不变。
  • 原始数据不变是什么意思?运行此代码后,test.csv 中将附加 5 个随机数。
猜你喜欢
  • 2010-11-18
  • 2014-07-20
  • 2012-05-10
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2013-05-26
  • 2012-02-04
  • 1970-01-01
相关资源
最近更新 更多