Python Code:
import datetime,os
data = ""
with open("D://PythonService//Test.txt", "w") as outFile:
outFile.write(data + "Service started at - {}n".format(datetime.datetime.now()))
outFile.close()
Dockerfile
FROM python:latest
COPY requirements.txt .
RUN python -m pip install -r requirements.txt
WORKDIR /app
COPY . /app
CMD ["python", "WriteData.py"]
docker-compose.yml
version: '3.4'
services:
newfoldercopy:
image: newfoldercopy
build:
context: .
dockerfile: ./Dockerfile
volumes:
- D:/PythonService:/var/lib/data/
I am trying to mount my physical file system path to the container.
But the container is not writing data on a physical file, the container is writing data on a container virtual file.
3
Answers
As I understand
D:/PythonService
– local path/var/lib/data/
– path inside containerIn Python code you should use container path (/var/lib/data/) not local path (D:/PythonService)
Your code should be something like
with open("/var/lib/data/Test.txt", "w") as outFile:
all files written at
/var/lib/data
folder inside the container will be available toD:/PythonService
Change:
to:
because of this line in your
docker-compose.yml
:Also instead of:
You can use
f-string
:which makes your code more readable.
Also as I understood, using
with open()
closes your file automatically, so you can change your Python code from:to: