Python django读取动态csv文件错误
我编写了Django python csv阅读器,但它工作不正常。我可以看到该文件已上载到系统,但我无法读取该文件,我得到以下错误:Python django读取动态csv文件错误,python,django,csv,Python,Django,Csv,我编写了Django python csv阅读器,但它工作不正常。我可以看到该文件已上载到系统,但我无法读取该文件,我得到以下错误: Exception Type: AttributeError Exception Value: 'str' object has no attribute 'read' data = csv.reader(open('tmp/tmp.csv'), delimiter=";") 当我按照上面的静态方式使用时,它正在工作,但我需要通过文件上传接收的动态文件
Exception Type: AttributeError
Exception Value: 'str' object has no attribute 'read'
data = csv.reader(open('tmp/tmp.csv'), delimiter=";")
当我按照上面的静态方式使用时,它正在工作,但我需要通过文件上传接收的动态文件。我需要你的帮助,因为我没有办法解决这个问题。
我知道解码的_文件、io_字符串和数据变量工作不正常,但无法修复它们
def upload_csv(request):
if request.method == 'POST' and request.FILES['csv_file']:
myfile = request.FILES['csv_file']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
decoded_file = filename.read().decode('utf-8')
io_string = io.StringIO(decoded_file)
data = csv.reader(io_string, delimiter=';', quotechar='|')
for row in data:
if row[0] != 'FP_Item':
post = FP()
post.FP_Item = row[0]
post.save()
CSV文件:不多,因为仍然导入试用,只有2行;最后,我还是删除并重试了
5.Item try
Try
您尝试在csv.reader中读取字符串。您可以在upload_csv中更改代码:
def upload_csv(request):
if request.method == 'POST' and request.FILES['csv_file']:
myfile = request.FILES['csv_file']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
print "filename",filename
data = csv.reader(fs.open(filename, mode='r'), delimiter=str(u';').encode('utf-8'), quotechar=str(u'"').encode('utf-8'))
for row in data:
print "row: ",row
我仍然收到相同的错误异常类型:AttributeError异常值:“str”对象没有属性“read”我在这一行收到此错误:decoded_file=filename.read()它不接受读取filename变量。这是什么原因?我编辑这一行:decoded_file=fs.open(filename)。请尝试告诉我worksfilename是否是要保存的文件名。您需要打开文件名为fs的文件。您在代码中更改了这一行:decoded_file=filename.read().decode('utf-8')这一行decoded_file=fs.open(filename.read().decode('utf-8')现在可以了。:)非常感谢您的关注。