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!'
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"
4条答案
按热度按时间2jcobegt1#
请尝试以下操作:
我还没有测试过这个,但是它已经从我以前写的一些代码中被提升和编译了。这将简单地阻止文件覆盖其他文件。注意:你将不得不自己修改文件名变量,然后保存文件,或者按照你的建议使用一些日期时间变量。我希望这在某种程度上有所帮助。
k75qkfdt2#
根据TaylorDay的建议,我对这个函数做了一些调整。下面的代码会询问你是否要覆盖一个现有的文件。如果不想,你可以键入另一个名称。然后,调用相同的write函数,它会再次检查
new_filename
是否存在。woobm2wo3#
对于3.3以上版本,请使用
mode='x'
来自文档:
以独占方式打开创建,如果文件已存在则失败
dgtucam14#