【问题标题】:How to write the SQL Server query output into .txt file using Python?如何使用 Python 将 SQL Server 查询输出写入 .txt 文件?
【发布时间】:2018-01-24 18:26:27
【问题描述】:

我是 Python 新手,正在尝试连接到 SQL Server 数据库并将查询的输出保存到一个平面 .txt 文件中。

一些代码正在运行,但只写入了近 1000 条记录,然后就停止了。

Python 版本:2.7.13。

下面的代码能够将所有 100 万条记录写入 csv 文件而不是 .txt 文件,这是问题所在。

import sys
print sys.path
import pyodbc
import pandas as pd
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=HCR046TW5SQL\HCRMIG50016;DATABASE=ENT;UID=pmatsa1;PWD=password@2015_1711;autocommit=True')
print 'Trying to assign cursor connection'
cursor = connection.cursor()
sql = """SELECT 
LEFT(ltrim(ISNULL(IN_OUT_BUILDING_NUM,' '))+REPLICATE(' ', 10) , 10)+
LEFT( ltrim(ISNULL(IN_OUT_ADR_ORIG_SHORT,' '))+REPLICATE(' ', 50) , 50)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_CITY,' '))+REPLICATE(' ', 28) , 28)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_STATE,' '))+REPLICATE(' ', 2) , 2)+
LEFT(ltrim(ISNULL(IN_OUT_ADR_ORIG_ZIP,' '))+REPLICATE(' ', 9) , 9)
 FROM ADDR_VAL_STAN_PB;"""
DataOut = open("Address_Validation_Input_File.txt", "a+")
cursor.execute(sql)

# Get data in batches
while True:
    # Read the data
    df = pd.DataFrame(cursor.fetchmany(1000))
    # We are done if there are no data
    if len(df) == 0:
        break
    # Let's write to the file
    else:
        df.to_csv(DataOut, header=False)

# Clean up
DataOut.close()
cursor.close()
connection.close()

【问题讨论】:

  • 尝试使用 fetchall() 而不是 fetchmany(1000)。它应该可以工作。
  • 嗨 Kaushik,我根本不想要 csv 文件作为输出。我只需要文本文件。我给出的代码是用于 csv,但我需要它在文本文件中。
  • Praveen 将此脚本从 CSV 输出转换为文本文件输出做了什么?在我看来,关于这个问题,(a)没有明确说明您的要求,以及(b)您没有尝试过任何事情。请注意,Stack Overflow 不是免费劳动力的票据交换所 - 我们需要您首先做出明确的努力。

标签: python sql-server flat-file


【解决方案1】:

在你的代码中用while下面的代码替换下面的代码:

df_csv=pd.DataFrame()
while True:
# Read the data
     df = pd.DataFrame(cursor.fetchall())
     # We are done if there are no data
     if len(df) == 0:
            break
     # Let's write to the file
     else:
          df_csv.append(df)
df_csv.to_csv('D:/path/test.txt', header=None, index=None, sep=' ', mode='a')

【讨论】:

  • 嗨 Kaushik,我根本不想要 csv 文件作为输出。我只需要文本文件。我给出的代码是用于 csv,但我需要它在文本文件中
  • 我已经编辑了代码,看看。如果有效,请选择答案。
猜你喜欢
  • 2021-02-07
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
相关资源
最近更新 更多