Django 中的 CSV 脚本看不到文件的路径 - [Errno 2] No such file or directory

The CSV script in Django does not see the path of the file - [Errno 2] No such file or directory

为什么我的 Python/Django 脚本无法读取文件路径? 如何正确获取已保存文件的路径?

[Errno 2] No such file or directory: '/media/file_hll8NoJ.csv

Views.py

if form.is_valid():
    cd = form.cleaned_data
    if cd['file']:
        obj = FileUpload()
        obj.file = cd['file']
        obj.save()
        with open(obj.file.url) as f:
            reader = csv.reader(f)
            for row in reader:
                _, created = UserEmail.objects.get_or_create(
                    owner=obj_instance,
                    email=row[0],
                    middle_name=row[2],
                )

路径正确,如果我打开 http://127.0.0.1:8000/media/file_hll8NoJ.csv 本地一切正常(我可以看到我的 csv 文件)

您正在访问文件的 url,如果您在客户端使用它是正确的,并且通常如果您从 Internet 访问资源。

但是,在这种情况下,您是从服务器端访问文件,您应该使用 obj.file.path 而不是 obj.file.url

来源:Django FieldFile Documentation