Rob*_*mer 11 python file-management python-2.7 export-to-csv pandas
当我分析数据时,我将我的数据帧保存到csv文件中并pd.to_csv()用于此目的.但是,函数(over)会写入新文件,而不检查是否存在具有相同名称的文件.有没有办法检查文件是否已经存在,如果是,请求新的文件名?
我知道我可以将系统的日期时间添加到文件名中,这可以防止任何覆盖,但我想知道我何时犯了错误.
joh*_*son 12
适合 3.3+ 使用mode='x'
来自文档:
打开以独占创建,如果文件已存在则失败
try:
df.to_csv('abc.csv', mode='x')
except FileExistsError:
df.to_csv('unique_name.csv')
Run Code Online (Sandbox Code Playgroud)
请尝试以下方法:
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!'
Run Code Online (Sandbox Code Playgroud)
我没有对此进行测试,但它已经从我之前编写的一些代码中解除并编译.这将简单地阻止文件覆盖其他人.注意,您必须自己更改文件名变量,然后保存文件,或者按照建议使用某个日期时间变量.我希望这在某种程度上有所帮助.
根据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"
Run Code Online (Sandbox Code Playgroud)