使用 Psycopg2 执行复制到数据库后文件对象为空
File Object is Empty after performing Copy to DB using Psycopg2
在下面的示例中,执行 copy_expert 命令后,文件内容似乎变空了,并且 pd.read_csv 抛出一个错误,指出它是一个空文件。即使我以相反的顺序执行此操作(read_csv 在 copy_expert 之前),该文件似乎也是空的。为什么文件是空的,我该如何处理这种情况?
file = //download file from S3
copy_sql = """
COPY %s FROM stdin WITH CSV HEADER
DELIMITER as ','
"""
cursor = self.connection.cursor()
cursor.copy_expert(sql=copy_sql % table_name, file=file)
cursor.close()
df = pd.read_csv(file, dtype={// dtype value})
编辑
我能够通过执行以下操作来解决它,但是这将有助于理解为什么文件对象被清空以及是否有更有效的方法来执行此操作。
file = //download file from S3
file_clone = copy.deepcopy(file)
copy_sql = """
COPY %s FROM stdin WITH CSV HEADER
DELIMITER as ','
"""
cursor = self.connection.cursor()
cursor.copy_expert(sql=copy_sql % table_name, file=file)
cursor.close()
df = pd.read_csv(file_clone, dtype={// dtype value})
问题是第一次读取文件数据后,file pointer
会在文件末尾;随后的读取调用将 return 没有数据。
为了能够再次读取数据,您需要将指针移动到文件的开头:
cursor.copy_expert(sql=copy_sql % table_name, file=file)
file.seek(0)
df = pd.read_csv(file, dtype={// dtype value})
在下面的示例中,执行 copy_expert 命令后,文件内容似乎变空了,并且 pd.read_csv 抛出一个错误,指出它是一个空文件。即使我以相反的顺序执行此操作(read_csv 在 copy_expert 之前),该文件似乎也是空的。为什么文件是空的,我该如何处理这种情况?
file = //download file from S3
copy_sql = """
COPY %s FROM stdin WITH CSV HEADER
DELIMITER as ','
"""
cursor = self.connection.cursor()
cursor.copy_expert(sql=copy_sql % table_name, file=file)
cursor.close()
df = pd.read_csv(file, dtype={// dtype value})
编辑
我能够通过执行以下操作来解决它,但是这将有助于理解为什么文件对象被清空以及是否有更有效的方法来执行此操作。
file = //download file from S3
file_clone = copy.deepcopy(file)
copy_sql = """
COPY %s FROM stdin WITH CSV HEADER
DELIMITER as ','
"""
cursor = self.connection.cursor()
cursor.copy_expert(sql=copy_sql % table_name, file=file)
cursor.close()
df = pd.read_csv(file_clone, dtype={// dtype value})
问题是第一次读取文件数据后,file pointer
会在文件末尾;随后的读取调用将 return 没有数据。
为了能够再次读取数据,您需要将指针移动到文件的开头:
cursor.copy_expert(sql=copy_sql % table_name, file=file)
file.seek(0)
df = pd.read_csv(file, dtype={// dtype value})