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

Exporting SQL query from Python to txt file

我正在尝试将从数据库中查询的数据导出到 txt 文件。我可以使用 .to_csv 方法执行此操作,但它会使用 spaces 导出。我试图将查询中的 (sep) 设置为 no space 但它迫使我至少使用一个 space 或项目作为分隔符。有什么方法可以将数据导出到 txt 文件并且在导出之间没有任何 spaces?

数据帧

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

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

希望它像这样导出:

尝试

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

如有任何问题,欢迎随时提问。

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

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')