删除以相同名称开头的旧文件

时间:2018-12-05 11:37:18

标签: python

我将查询内容存储在CSV文件中。在存储之前,我想删除所有以旧名称开头(例如“ DF_Tripheader”)的查询。我以此为灵感:“ Deleting files which start with a name Python”,但它不起作用。我没有收到错误,但较旧的文件也没有被删除。有人可以帮我吗?

Queries = {"DF_TripHeader":DF_TripHeader,"DF_AM":DF_AM}
SQL_Folder = 'SQL_RawData/'

def get_data_from_sql():
    if not os.path.exists(SQL_Folder):
        os.makedirs(SQL_Folder)

   for Query_Name, Query in Queries.items():
     if not os.path.exists(SQL_Folder + '{}_'.format(Query_Name) + str(date.today()) +'.csv'):

        for filename in glob.glob('"' + SQL_Folder + Query_Name + '*"'): #here is the problem
            os.remove(filename)

        Query_CSV = pd.read_sql_query(Query,Conn_SQL)
        Query_CSV.to_csv(SQL_Folder + '{}_'.format(Query_Name) + str(date.today()) +'.csv')
        print('{} downloaded successful'.format(Query_Name))
    else:
        print('Already downloaded {}'.format(Query_Name))

get_data_from_sql()

编辑:Kishor Pawar设法解决了这个问题,非常感谢!

Queries = {"SQL_TripHeader":SQL_TripHeader,"SQL_AM":SQL_AM}
SQL_Folder = 'SQL_RawData/'
Date = str(date.today())


def get_data_from_sql():
if not os.path.exists(SQL_Folder):
    os.makedirs(SQL_Folder)

for Query_Name, Query in Queries.items():
    if not os.path.exists(SQL_Folder + '{}_'.format(Query_Name) + Date +'.csv'):
        for filename in glob.glob("{0}{1}*".format(SQL_Folder, Query_Name)):
            try:
                os.remove(filename)
            except:
                print('x')
        Query_CSV = pd.read_sql_query(Query,Conn_SQL)
        Query_CSV.to_csv(SQL_Folder + '{}_'.format(Query_Name) + Date +'.csv')
        print('{} downloaded successful'.format(Query_Name))
    else:
        print('Already downloaded {}'.format(Query_Name))
get_data_from_sql()

1 个答案:

答案 0 :(得分:1)

好的。从您的评论中,我发现了以下内容。

您的错误是"SQL_RawData/DF_TripHeader*",实际上应该是"SQL_RawData/DF_TripHeader/*" #notice the slash before *

glob.glob返回pathname中传递的路径匹配列表。我不知道您通过"SQL_RawData/DF_TripHeader*"时返回了什么。但是当您通过"SQL_RawData/DF_TripHeader/*"时,它将返回所有文件名。

此外,请注意,glob.glob将返回filenames的列表。您需要将实际路径传递到os.remove