【发布时间】:2021-02-14 19:12:48
【问题描述】:
我一直在开发一个 Django 应用程序。我知道读取 SPSS 文件有一些不同。一种方法是使用 pandas。
import pandas as pd
file_path = "./my_spss_file.sav"
df = pd.read_spss(file_path)
另一种方法是使用 pyreadstat
import pyreadstat
df, meta = pyreadstat.read_sav('./my_spss_file.sav')
正如您在上面看到的,与 pandas 不同,使用 pyreadstat 我可以获得元信息,例如变量和标签值。所以,这就是我正在使用的。这个 pyreadstat 的问题是我不能将它用于内存读取。从浏览器上传一个spss文件后,每次我都必须将它上传到一个目录,然后使用pyreadstat模块从那里读取文件。
def upload_file(request):
result = None
# Get the context from the request.
context = RequestContext(request)
if request.is_ajax():
if "POST" == request.method:
global my_df
global _explore
global base_dir
file = request.FILES['file']
file_name = file.name
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
try:
my_df = None
# Determine the type of the file and get the dataframe
if file_name.endswith('.csv'):
my_df = pd.read_csv(file, header=0)
elif file_name.endswith('.xlsx') or file_name.endswith('.xls'):
my_df = pd.read_excel(file, header=0)
elif file_name.endswith('.sav') or file_name.endswith('.zsav'):
handle_uploaded_file(file, str(file))
file_path = os.path.join(base_dir, "upload\\") + file_name
my_df = util.read_spss_file(file_path)
def read_spss_file(f_name):
df, meta = pyreadstat.read_sav(f_name, apply_value_formats=True)
return df
def handle_uploaded_file(file, filename):
upload_dir = os.path.join(base_dir, "upload\\") #base_dir + 'upload/'
if not os.path.exists(upload_dir):
os.mkdir(upload_dir)
with open(upload_dir + filename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
我不想将上传的 spss 文件写入磁盘。所以,我想知道是否有办法使用 pyreadstat 模块读取内存中的 spss 文件?
【问题讨论】:
标签: python django readfile spss