简体   繁体   中英

Python/Docker : FileNotFoundError: [Errno 2] No such file or directory:

I am using a Python code to open a text file and write some information and close it. When I run this code on Jupyter notebook it runs perfectly but when I run this as a part of Docker container it gives the following error.

Current directory is C:/app where I have stored Dockerfile, testfile.txt and Hello1.py. In addition I have gone to Virtual Machine and have added C: as shared folder.

Python File

  file = open("C:/Python/testfile.txt","w")
  file.write("Hello World")
  file.write("This is our new text file")
  file.close()

Docker File

 FROM python:latest
 WORKDIR /data
 COPY testfile.txt /data
 COPY Hello1.py /data
 CMD ["python","Hello1.py"]

Error Recieved

 $ docker run sid1980
 Traceback (most recent call last):
 File "Hello1.py", line 7, in <module>
 file = open("C:/Python/testfile.txt","w")
 FileNotFoundError: [Errno 2] No such file or directory: 'C:/Python/testfile.txt'

Your python program cannot access C:/ of the host machine. You need to change the file path to reference the testfile.txt that exists within the container .

file = open("/data/testfile.txt","w")

Also note that this will not modify the testfile.txt that exists on the host. It will write to the file that is inside the container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM