gpt4 book ai didi

python - django读取动态csv文件错误

转载 作者:行者123 更新时间:2023-12-01 02:00:56 24 4
gpt4 key购买 nike

我编写了 Django python csv reader,但它无法正常工作。我可以看到文件已上传到系统,但我无法读取它,并且收到以下错误:

Exception Type: AttributeError 
Exception Value: 'str' object has no attribute 'read'
data = csv.reader(open('tmp/tmp.csv'), delimiter=";")

当我按照上面的方式静态使用时,它可以工作,但我需要通过文件上传接收的动态。我需要你的帮助,因为我没有办法解决这个问题。我知道解码的文件、io_string 和数据变量无法正常工作,但无法修复它们。

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

关于python - django读取动态csv文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49636987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com