将 SQL 查询从 Python 导出到 txt 文件

Posted

技术标签:

【中文标题】将 SQL 查询从 Python 导出到 txt 文件【英文标题】:Exporting SQL query from Python to txt file 【发布时间】:2021-03-31 18:36:29 【问题描述】:

我正在尝试将我从数据库查询的数据导出到 txt 文件。我可以使用 .to_csv 方法来做到这一点,但是它使用空格导出。我试图将查询中的 (sep) 设置为无空格,但它迫使我至少使用一个空格或项目作为分隔符。有什么办法可以将数据导出到txt文件,而且导出之间没有空格?

数据框

我一直用来导出到 .txt 的代码

dataframe.to_csv('Sales_Drivers_ITCSignup.txt',index=False,header=True)

希望它像这样导出:

【问题讨论】:

有什么理由不想要分隔符?任何这些字段中的任何一个字符(例如,甚至更短或更长)都会使再次读回变得很棘手......或者你真的想要一个固定宽度的文件? 我们将此列表发送给 IT 团队以进行转换。不确定具体原因,但这是他们要求我们发送的格式。 【参考方案1】:

试试

np.savetext(filename, df.values, fmt)

如有任何问题,请随时提出问题。

【讨论】:

我尝试使用这个 'np.savetxt("Sales_Drivers_ITCSignup_2.txt", dataframe.values, fmt='')' 但得到 fmt 的 % 格式数量错误的错误。我该如何解决这个问题? Format 'fmt' 是您定义值所包含的数据类型的地方,就像 '%d' 或 '%s' 您可以为单独的列定义单独的 fmt,也可以为所有列定义通用的。你应该为你的“%s”。【参考方案2】:

进行了一些修改,但这是我能够想出的代码。思考过程是创建导入文本文件,将其编辑为列表,然后重新导出它以覆盖先前的列表。谢谢大家的建议!

RemoveCommas = []
RemoveSpaces = []
AddSymbol = []
Removeextra = []

#Import List and execute replacements
SalesDriversTransactions = []
with open('Sales_Drivers_Transactions.txt', 'r')as reader:
    for line in reader.readlines():
        SalesDriversTransactions.append(line)

for comma in SalesDriversTransactions:
    WhatWeNeed = comma.replace(",","")
    RemoveCommas.append(WhatWeNeed)
    
for comma in RemoveCommas:
    WhatWeNeed = comma.replace(" ","")
    RemoveSpaces.append(WhatWeNeed)
    
for comma in RemoveSpaces:
    WhatWeNeed = comma.replace("þ","þ")
    AddSymbol.append(WhatWeNeed)

for comma in AddSymbol:
    WhatWeNeed = comma.replace("\n","")
    Removeextra.append(WhatWeNeed)

with open('Sales_Drivers_Transactions.txt', 'w')as f:
    for i in Removeextra:
        f.write(i)
        f.write('\n')

【讨论】:

以上是关于将 SQL 查询从 Python 导出到 txt 文件的主要内容,如果未能解决你的问题,请参考以下文章

将 SQL 查询结果作为 txt 文件自动导出到 Azure Blob 存储

SQL Server:将查询导出为 .txt 文件

使用 VBA 或 PowerShell 将所有 MS Access SQL 查询导出到文本文件

oracle/mysql 将查询数据导出到文件中

Python 导出到 TXT 格式或剪贴板

Python将依赖包导出到requirements.txt文件