你好在媒体文件夹中上传csv文件,现在我想把这些文件传递给python中的一个列表来制作一个pdf。我怎样才能在django的函数中调用这些文件,或者有更好的方法可以做到这一点?
这是我上传文件的方式:
def subir_archivos(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'subir_csv.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'subir_csv.html')
将csv传递给python列表的方法:
def csv_empresas(request):
lista = []
with open('media/empresas.csv') as csvfile:
lector = csv.reader(csvfile, delimiter=',',quotechar='|')
for row in lector:
lista.append(row)
return render(request,'preparar_pdf.html',{"lista": lista})
答案 0 :(得分:0)
上传文件时,您可以将所有上传的文件保存在媒体文件夹
中的一个文件夹中将上传文件保存在名为upload_files
def subir_archivos(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
file_obj = myfile.read()
media_path = settings.MEDIA_ROOT
file_path= os.path.join(media_path, "upload_files")
if not os.path.isdir(file_path):
try:
os.makedir(file_path)
except OSError as e:
pass
file = os.path.join(file_path, myfile.name)
with open(file, 'wb') as f:
f.write(file_obj)
uploaded_file_url = os.path.join("/media", "upload_files", myfile.name)
return render(request, 'subir_csv.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'subir_csv.html')
以及获取所有上传文件的代码
import os
def csv_empresas(request):
lista = []
media_path = settings.MEDIA_ROOT
file_path= os.path.join(media_path, "upload_files")
files = os.listdir(file_path)
for file in files:
with open(file, 'rb') as csvfile:
lector = csv.reader(csvfile, delimiter=',',quotechar='|')
for row in lector:
lista.append(row)
return render(request,'preparar_pdf.html',{"lista": lista})