代码之家  ›  专栏  ›  技术社区  ›  William

Docker FileNotFoundError:[Erno 2]没有这样的文件或目录

  •  0
  • William  · 技术社区  · 2 年前

    我对docker很陌生。我正在使用docker和pandas读取csv文件并插入数据库。

    Dockerfile(码头文件):

    FROM python:3.8
    
    ADD main.py .
    
    RUN pip install requests pandas sqlalchemy
    
    CMD ["python","./main.py"]
    

    主要.py:

    进口

    import pandas as pd
    from sqlalchemy import create_engine
    
    # This CSV doesn't have a header so pass
    # column names as an argument
    columns = [
        "open",
        "high",
        "low",
        "close",
        "volume",
        "datetime",
    ]
    
    # Load in the data
    df = pd.read_csv(r"/Users/myname/Downloads/file511282022.csv",names=columns)
    
    # Instantiate sqlachemy.create_engine object
    engine = create_engine('postgresql://postgres:mypassword@localhost:5432/postgres')
    
    # Save the data from dataframe to
    # postgres table "iris_dataset"
    df.to_sql(
        'file5', 
        engine,
    #     index=False # Not copying over the index
    )
    

    错误:

    FileNotFoundError: [Errno 2] No such file or directory: '/Users/myname/Downloads/file511282022.csv'
    

    pd.readcsv代码在jupter笔记本中的docker中运行,代码相同:

    pd.read_csv(r"/Users/myname/Downloads/file511282022.csv",names=columns)
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Hiren Namera    2 年前

    需要在docker中添加csv文件,因为docker有自己的文件路径,您无法访问本地文件(在docker运行命令中添加的除外)。所以,您需要将该文件也添加到docker中,与main.py文件相同。

    FROM python:3.8
    
    ADD main.py .
    ADD file511282022.csv .
    
    RUN pip install requests pandas sqlalchemy
    
    CMD ["python","./main.py"]
    

    import pandas as pd
    from sqlalchemy import create_engine
    
    # This CSV doesn't have a header so pass
    # column names as an argument
    columns = [
        "open",
        "high",
        "low",
        "close",
        "volume",
        "datetime",
    ]
    
    # Load in the data
    df = pd.read_csv("file511282022.csv",names=columns)
    
    # Instantiate sqlachemy.create_engine object
    engine = create_engine('postgresql://postgres:mypassword@localhost:5432/postgres')
    
    # Save the data from dataframe to
    # postgres table "iris_dataset"
    df.to_sql(
        'file5', 
        engine,
    #     index=False # Not copying over the index
    )
    

    此外,您还需要更改engine=create_engine('postgresql://postgres:mypassword@localhost:5432/postgres')

    使用docker网络。