You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署至主机后读取Media文件夹CSV文件出现FileNotFoundError求助

部署后读取Media文件夹CSV文件触发FileNotFoundError的解决方法

问题描述

部署应用至主机后,读取Media文件夹中的CSV文件时触发FileNotFoundError,报错信息:

[Errno 2] No such file or directory: '/home/ed/public_html/myproject/project\media\A.csv'

本地运行正常,相关配置及代码如下:

settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

if DEBUG:
    STATICFILES_DIRS = ['/home/ed/public_html/myproject/project/static']
else:
   STATIC_ROOT = '/home/ed/public_html/myproject/project/static'

MEDIA_ROOT = '/home/ed/public_html/myproject/project/media'

urls.py

urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

views.py

def test(request):
    context = {}
    if request.method == "POST":
        uploaded_file = request.FILES['document']
        print(uploaded_file)
        if uploaded_file.name.endswith('.csv'):
            #save file in media folder
            savefile = FileSystemStorage()
            name = savefile.save(uploaded_file.name, uploaded_file) #name of the file
            #know where to save file
            d = os.getcwd() #current directory of the project
            file_directory = d + '\media\\' + name
            readfile(file_directory)
            return redirect(results)
       else:
             messages.warning(request, 'File was not uploaded. Please use csv file!')

    return render(request, 'test.html', {})

问题排查与解决

核心原因

报错路径混合了Linux正斜杠/和Windows反斜杠\,这是因为代码硬编码反斜杠拼接路径,本地Windows环境兼容,但部署到Linux主机后路径格式不匹配。同时,os.getcwd()获取的当前目录不可靠,服务器运行时工作目录未必是项目根目录。

修复方案

  1. 利用Django配置的MEDIA_ROOT拼接路径
    直接调用settings.MEDIA_ROOT结合os.path.join()构建正确路径,避免手动拼接和依赖当前工作目录:
    from django.conf import settings
    import os
    
    def test(request):
        context = {}
        if request.method == "POST":
            uploaded_file = request.FILES['document']
            print(uploaded_file)
            if uploaded_file.name.endswith('.csv'):
                savefile = FileSystemStorage()
                name = savefile.save(uploaded_file.name, uploaded_file)
                # 用os.path.join自动适配路径分隔符
                file_directory = os.path.join(settings.MEDIA_ROOT, name)
                readfile(file_directory)
                return redirect(results)
            else:
                messages.warning(request, 'File was not uploaded. Please use csv file!')
    
        return render(request, 'test.html', {})
    
  2. 显式指定FileSystemStorage的根目录(可选)
    若需明确存储位置,可给FileSystemStorage传入location参数:
    savefile = FileSystemStorage(location=settings.MEDIA_ROOT)
    
  3. 验证路径格式
    修复后生成的路径为Linux兼容格式/home/ed/public_html/myproject/project/media/A.csv,不会再出现混合斜杠问题。

额外注意事项

  • 始终使用os.path.join()拼接路径,它会根据操作系统自动选择正确的路径分隔符。
  • 避免依赖os.getcwd(),服务器进程的工作目录可能与项目根目录不一致,优先使用Django配置的路径常量。

内容的提问来源于stack exchange,提问作者OmarDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:30:55