Pandas to_csv() 检查覆盖

Pandas to_csv() checking for overwrite

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

我知道我可以将系统的日期时间添加到文件名中,这样可以防止任何覆盖,但我想知道我是什么时候出错的。

尝试以下操作:

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!' 

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

根据TaylorDay的建议我对函数做了一些调整。使用以下代码,系统会询问您是否要覆盖现有文件。如果不是,您可以输入另一个名称。然后,调用相同的写入函数,它将再次检查 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"