访问从Djang上传的文件

2024-04-18 01:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设计一个允许用户上传.xls文件的web应用程序。上传时,应该保存文件,并将其转换为.csv文件,然后通过python导入脚本导入文件中包含的数据。你知道吗

所有用于导入和转换数据的函数都在shell中完全起作用,但是当通过本地主机进行测试时,文件将转换为.csv并保存,但没有脚本在新文件上运行。你知道吗

从视图.py地址:

    #for uploading data on the dashboard
    def file_upload(request):
        if request.method == 'POST':
            save_path = os.path.join(str(settings.MEDIA_ROOT), 'uploads', str(request.FILES['file']))
            try:
                validate_file_extension(request.FILES['file'])
                path = default_storage.save(save_path, request.FILES['file'])
                data = xls_to_csv(save_path, str(settings.MEDIA_ROOT))
                create_athlete(data, filename)
                create_phase(data)
                create_health_report(data)
                create_workout_report(data)
            except:
                return redirect('polar:dashboard')
            return redirect('polar:dashboard')

从导入脚本.py你知道吗

    def xls_to_csv(file_name, save_path):
        #Formats into pandas dataframe.
        formatted_dataframe = pd.read_excel(file_name, index_col=None)
        #Converts the formatted into a csv file and save it.
        file_name = file_name.replace('.xls', '.csv')
        new_file = formatted_dataframe.to_csv(file_name))
        module_dir = os.path.dirname(settings.BASE_DIR)
        file_path = os.path.join(module_dir, 'uploads', file_name)
        sample_data = open(file_name, 'r')
        unfiltered_data = sample_data.readlines()
        data = unfiltered_data[1:]
        return data

就好像Django正在阻止新创建的.csv文件被打开和读取。任何关于解决这个问题的建议都将不胜感激!你知道吗


Tags: 文件csvpathname脚本datasettingsos
1条回答
网友
1楼 · 发布于 2024-04-18 01:09:50

如果在Linux或Mac环境下工作,那么授予上传目录读写权限是很重要的。 或者,如果这不是问题,那么似乎您在处理xls到CSV文件时遇到了问题,请看这个

import xlrd
import unicodecsv

def xls2csv (xls_filename, csv_filename):
    # Converts an Excel file to a CSV file.
    # If the excel file has multiple worksheets, only the first 
    #worksheet is converted.
    # Uses unicodecsv, so it will handle Unicode characters.
    # Uses a recent version of xlrd, so it should handle old .xls and 
   # new 
   #.xlsx equally well.

   wb = xlrd.open_workbook(xls_filename)
   sh = wb.sheet_by_index(0)

   fh = open(csv_filename,"wb")
   csv_out = unicodecsv.writer(fh, encoding='utf-8')

   for row_number in xrange (sh.nrows):
       csv_out.writerow(sh.row_values(row_number))

   fh.close()

取自here

相关问题 更多 >

    热门问题