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

2024-09-17 18:27:20 发布

您现在位置: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_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

Tags: 文件csvin程序fordbsql格式