Reputation: 1191
Wondering how to create a file from inside a docker container.
For example in this project I aim to create a text file. I get confirmation that the process is done, however, there's no txt file.
import logging
import os
logging.basicConfig(format='%(asctime)s - [%(processName)s - %(threadName)s] %(name)s - %(levelname)s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S", level=os.getenv('LOGLEVEL', 'INFO'))
logger = logging.getLogger(__name__)
f= open("example.txt","w+")
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
f.close()
logger.info(f'Successfully created text file.')
What am I doing wrong?
Upvotes: 0
Views: 930
Reputation: 40416
The most effective way to share files between a host and a container running on it, is to use volume mounts. It's convenient to keep such volumes distinct.
For argument's sake:
Assuming you're in your project's root, mkdir ./data
to create a directory at the same level as your ./src
folder.
Change your code (to prove the point) to open("/aha/example.txt","w+")
. NB Yes, /aha
not /data
... keep reading.
Run the container and mount the host's (!) ./data
into the container as ./aha
: docker run --interactive --tty --volume=${PWD}/data:/aha ...
. NB This mounts the host's ${PWD}/data
into the container as a directory /aha
. IIRC you must use ${PWD}
to provide an absolute path
Once the Python code completes, the container will have a file called /aha/example.txt
and your host (!) should include a file called ${PWD}/data/example.txt
Upvotes: 2