Python PostgresQL-导出到CSV,而不是导出所有行

Python PostgresQL-导出到CSV,而不是导出所有行,python,python-3.x,postgresql,csv,export-to-csv,Python,Python 3.x,Postgresql,Csv,Export To Csv,我有一个Postgresql查询,我想用Python运行它并将其导出到CSV文件 我对Python非常陌生,但我已经编写了一个脚本,可以运行查询并导出到文件 import psycopg2 # File path and name. fileName = 'test.csv' # Database connection variable. connect = None # Check if the file path exists. if os.path.exists(filePath)

我有一个Postgresql查询,我想用Python运行它并将其导出到CSV文件

我对Python非常陌生,但我已经编写了一个脚本,可以运行查询并导出到文件

import psycopg2

# File path and name.
fileName = 'test.csv'


# Database connection variable.
connect = None

# Check if the file path exists.
if os.path.exists(filePath):

    try:

        # Connect to database.
        connect = psycopg2.connect(host="xxxx", port="5439", database="xxxx", user="xxxx", password="xxxx")

    except psycopg2.DatabaseError as e:

        # Confirm unsuccessful connection and stop program execution.
        print("Database connection unsuccessful.")
        quit()

    # Cursor to execute query.
    cursor = connect.cursor()

    # SQL to select data from the person table.
    sqlSelect = """
SELECT * FROM TABLE
                """

    try:

        # Execute query.
        cursor.execute(sqlSelect)

        # Fetch the data returned.
        results = cursor.fetchall()

        # Extract the table headers.
        headers = [i[0] for i in cursor.description]

        #Print the results
        #print(pd.read_sql(sqlSelect, connect))
        print(tb.tabulate(results, headers=headers, tablefmt='psql', showindex="always", floatfmt=".10f"))

        # Open CSV file for writing.
        csvFile = csv.writer(open(filePath + fileName, 'w', newline=''),
                             delimiter=',', lineterminator='\r\n',
                             quoting=csv.QUOTE_ALL, escapechar='\\')

        # Add the headers and data to the CSV file.
        csvFile.writerow(headers)

        for row in results:
            csvFile.writerow(row)

        # Message stating export successful.
        print("Data export successful.")

        # csvFile.close()

    except psycopg2.DatabaseError as e:

        # Message stating export unsuccessful.
        print("Data export unsuccessful.")
        quit()

    finally:

        # Close database connection.
        cursor.close()
        connect.close()

else:

    # Message stating file path does not exist.
    print("File path does not exist.")


cursor.close()
connect.close()
我运行的查询生成70行结果(当我通过数据库程序运行它时)。但是,当我将数据导出到CSV时,它只导出48行


我想不出哪里出了问题。

你的代码在postgres中有490行

可能您的问题在于数据库中的某个记录具有某些特殊字符,导致代码停止并无法获得预期结果


调试脚本,添加异常打印以检查是否存在问题。

可能是因为您没有关闭csvFile?无论如何,我建议在psycopg2的游标类中使用内置的copy_to。它将为您创建csv文件。谢谢!好地方。我使用了
with
语句,它在导出数据后关闭文件。我打印了结果,结果有70行,但导出工作不正常。杰里米找到了解决办法。谢谢你花时间回答我的问题。不客气,我很高兴你能用杰里米的解决方案解决你的问题