我有一个很大的sql文件(20 GB),我想将其转换为csv。我计划将文件加载到Stata中进行分析。我有足够的内存来加载整个文件(我的计算机具有32GB的RAM)
问题是:到目前为止,我在网上使用Python(sqlite3)找到的解决方案似乎需要比当前系统更多的RAM:
这是代码
import sqlite3
import pandas as pd
con=sqlite3.connect('mydata.sql')
query='select * from mydata'
data=pd.read_sql(query,con)
data.to_csv('export.csv')
con.close()
sql文件包含大约15个变量,可以是时间戳,字符串或数字值。没什么好看的。
我认为一种可能的解决方案可能是一次读取sql并将csv文件写入一行。但是,我不知道该怎么做(在R或Python中)
任何帮助真的很感激!
您可以批量读取SQL数据库并将其写入文件,而不必一次读取整个数据库。归功于如何将熊猫数据添加到现有的csv文件中?有关如何添加到现有CSV文件的信息。
import sqlite3
import pandas as pd
# Open the file
f = open('output.csv', 'w')
# Create a connection and get a cursor
connection = sqlite3.connect('mydata.sql')
cursor = connection.cursor()
# Execute the query
cursor.execute('select * from mydata')
# 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(f, header=False)
# Clean up
f.close()
cursor.close()
connection.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句