我正在设计一个网络应用程序,允许用户上传一个.xls文件。上传时,应将文件保存并转换为.csv文件,然后文件中包含的数据将通过python导入脚本导入。
所有用于导入和转换数据的功能在shell中都是完整的,但是,当通过本地主机进行测试时,文件将转换为.csv并保存,但没有脚本在新文件上运行。
来自views.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')
来自importscript.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文件被打开和读取一样。任何关于解决这个问题的技巧都将不胜感激!
发布于 2018-06-09 03:33:21
如果在Linux或Mac环境中工作,那么授予上传目录读写权限是很重要的。或者,如果这不是问题所在,那么您似乎在处理xls to 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
https://stackoverflow.com/questions/50767257
复制相似问题