Reputation: 151
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'
Upvotes: 5
Views: 29629
Reputation: 423
I was having a very similar error and just fixed it, so I hope this answer helps.
So, what happens is when you do docker run IMAGE
, and your code inside the image accesses a file, it is relative to the root of the image.
So if your actual fd looks like this:
Python
testfile.txt
And the fd in your image looks like this:
directory
randomfile.txt
Then, you are going to get an error, because there is no Python
directory, much less a testfile.txt
, inside the image.
So, what you can do, at least in Mac, is that you can use the --volume
flag when doing docker run
to specify where you want to local file to appear in the docker image. For example, you can do something like docker run --name IMAGENAME --volume /Python:/usr/directory/Python
to have your Python folder be staged at /usr/directory/Python
inside the image. Then, you can use the "staged" folder in your code by writing in your code something like
file = open("C:/usr/Python/testfile.txt","w")
(Not sure exactly what the root of the image is considered on Windows, so use pwd
to confirm)
Of course, change the argument for where you want the folder/file to appear in the image to your needs. This link was pretty helpful when I was solving this problem: https://docs.docker.com/storage/volumes/#choose-the--v-or---mount-flag.
P.S. If you want to see what the file directory of your image looks like, you can do docker exec IMAGENAME bash
after docker run
ning it.
Upvotes: 4
Reputation: 4423
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.
Upvotes: 2