如何在不删除文件的情况下终止python编程过程

如何在不删除文件的情况下终止python编程过程,python,Python,我是python初学者,我有一个问题,我运行python程序,该程序用于将日志文件从gz格式保存为csv格式,但不幸的是,当我试图终止该程序时,我强制终止该程序,这使得该文件无法写入我的计算机,因此,如何在不删除文件的情况下手动终止。下面是我的代码: # List of all gz files gz_files = (gz for gz in glob.glob(os.path.join(GZ_DIR, '*.gz'))) # Loop through all gz files for gz

我是python初学者,我有一个问题,我运行python程序,该程序用于将日志文件从gz格式保存为csv格式,但不幸的是,当我试图终止该程序时,我强制终止该程序,这使得该文件无法写入我的计算机,因此,如何在不删除文件的情况下手动终止。下面是我的代码:

# List of all gz files
gz_files = (gz for gz in glob.glob(os.path.join(GZ_DIR, '*.gz')))

# Loop through all gz files
for gz_file in gz_files:
    sql_file = gz_file[:-3]
    sql_file = sql_file[:-4] + '.csv'
    with open(sql_file, 'wb') as out_file:
        with gzip.open(gz_file, 'rb') as in_file:
            while True:
                chunk = in_file.read(1024)
                if not chunk:
                    break
                out_file.write(chunk)

    # Step 2: import to sql
    import_sql(out_file, DB_HOST, DB_USER, DB_PASS, DB_NAME)

    # Step 3: remove uncompresed file
    # os.remove(sql_file)

    # Step 4: in loop, back to step 1 automatically for another gz files

您是否尝试过显式地
open()
文件,从而在每次gzfile迭代中都不使用
flush()
写入的内容?看看这个:我认为您应该优雅地关闭程序,您可以捕获
crtl-c
信号,然后优雅地关闭文件