【问题标题】:Pandas to_csv() checking for overwritePandas to_csv() 检查覆盖
【发布时间】:2017-03-15 11:52:54
【问题描述】:

当我分析数据时,我将我的数据框保存到一个 csv 文件中,并为此使用 pd.to_csv()。但是,该函数(覆盖)写入新文件,而不检查是否存在同名文件。 有没有办法检查文件是否已经存在,如果存在,要求一个新的文件名?

我知道我可以将系统的日期时间添加到文件名中,这将防止任何覆盖,但我想知道我何时犯了错误。

【问题讨论】:

  • 欢迎反馈我如何改进这个问题。请选民解释他的反对票吗?我很乐意做一些调整。
  • 我不是反对你的人,但我猜是因为答案很可能来自谷歌搜索?
  • 不幸的是它没有,但我必须说我正在寻找内置的 Pandas 或其他东西。没想过一个简单的 if 语句。

标签: python python-2.7 pandas export-to-csv file-management


【解决方案1】:

根据 TaylorDay 的建议,我对该功能进行了一些调整。使用以下代码,系统会询问您是否要覆盖现有文件。如果没有,您可以输入另一个名称。然后,同样的 write-function 被调用,它会再次检查new_filename 是否存在。

from os import path
import pandas as pd
def write_csv_df(path, filename, df):
    # Give the filename you wish to save the file to
    pathfile = os.path.normpath(os.path.join(path,filename))

    # Use this function to search for any files which match your filename
    files_present = os.path.isfile(pathfile) 
    # if no matching files, write to csv, if there are matching files, print statement
    if not files_present:
        df.to_csv(pathfile, sep=';')
    else:
        overwrite = raw_input("WARNING: " + pathfile + " already exists! Do you want to overwrite <y/n>? \n ")
        if overwrite == 'y':
            df.to_csv(pathfile, sep=';')
        elif overwrite == 'n':
            new_filename = raw_input("Type new filename: \n ")
            write_csv_df(path,new_filename,df)
        else:
            print "Not a valid input. Data is NOT saved!\n"

【讨论】:

    【解决方案2】:

    尝试以下方法:

    import glob
    import pandas as pd
    
    # Give the filename you wish to save the file to
    filename = 'Your_filename.csv'
    
    # Use this function to search for any files which match your filename
    files_present = glob.glob(filename)
    
    
    # if no matching files, write to csv, if there are matching files, print statement
    if not files_present:
        pd.to_csv(filename)
    else:
        print 'WARNING: This file already exists!' 
    

    我没有对此进行测试,但它已从我之前编写的一些代码中提取和编译。这将简单地停止文件覆盖其他文件。注:您必须自己更改文件名变量才能保存文件,或者按照您的建议使用一些日期时间变量。我希望这在某种程度上有所帮助。

    【讨论】:

    • 非常感谢。这是一个非常简单的解决方案:)
    • os.path.exists() 是一种更简单的检查路径是否存在的方法。但这种方法是Time of Check to Time of Use 错误的经典来源。尝试使用pd.to_csv(filename, mode='x'),如果目标文件存在,则会引发异常。
    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2022-06-13
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多