You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python-Oracle脚本未能导出Oracle全表数据问题求助

问题原因及修复方案

你的脚本存在两个关键问题,直接导致数据导出不全:

1. 文件写入模式错误

循环中使用mode='w+',该模式每次打开文件时都会清空原有内容再写入。因此每处理一个数据块,之前写入的内容都会被覆盖,最终文件仅保留最后一个数据块的内容(也就是你看到的985,000行左右)。

2. 表头重复写入(次要但需修复)

每次循环都设置header=True,如果直接改成追加模式,会导致每个数据块开头都重复写入表头,不符合导出需求。


修复后的代码

import datetime
import arrow
import cx_Oracle
import pandas as pd
import numpy
import os.path
import warnings

warnings.filterwarnings('ignore')

cx_Oracle.init_oracle_client(lib_dir=r"xxxxxxx")

dsn_tns = cx_Oracle.makedsn('xxxxxxxxx')
conn = cx_Oracle.connect(user=r'xxxxx', password='xxxxx',dsn=xxxx)  

current_date = arrow.now().format('YYYYMMDD')
year = datetime.datetime.now().strftime('%Y')
month = datetime.datetime.now().strftime('%B')
directory = "\\xxxxx\\CY{}\\{}{}\\".format(year, month, year)

# 提前创建目录,避免因目录不存在导致写入失败
os.makedirs(directory, exist_ok=True)

SQL_QUERY = pd.read_sql_query("SELECT * FROM CLINICAL_LAB_SUPP ", conn, chunksize=1000000)

file1 = directory + "MyFile_{}.txt".format(current_date)

first_write = True

for df_chunk in SQL_QUERY:
    df = pd.DataFrame(df_chunk)
    # 第一次写入用w+创建文件并写表头,后续用a+追加且不写表头
    mode = 'w+' if first_write else 'a+'
    df.to_csv(file1, index=False, header=first_write, mode=mode, sep='\t')
    first_write = False

额外说明

  • 新增os.makedirs(directory, exist_ok=True)确保输出目录存在,避免因目录未创建导致的写入失败
  • 移除了未使用的变量i,精简代码逻辑

内容的提问来源于stack exchange,提问作者kfire35

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:12:56