File not found in a created directory

76 Views Asked by At

I am working to add a file in temporary folder like so:

self._dir = tempfile.mkdtemp()
self._dir = os.path.join(self._dir, "test")
os.mkdir(self._dir)
self.checkpoint = os.path.join(self._dir, "file.txt")

So the above in the init function.

and when I call my main function, I only see the test folder and there is no file.txt along with it.

how can i solve this?

4

There are 4 best solutions below

1
Luke On

Based on the code you have provided, that is the expected behaviour.

os.mkdir creates the directory, but there is no other code to create a text file - os.path.join only joins two or more filenames into one combined filename, it doesn't create anything.

If you want to create the text file, you would probably need to add something like

f = open(self.checkpoint, "w") #create a new blank file
f.close() #close it so we're not leaving the handle open
0
Lee-xp On

You have not actually created the file, just generated a filepath. Try this.

import os

checkpoint = os.path.join('.', "file.txt")

f = open(checkpoint, 'w')
f.close()

It will create the file in the current directory.

0
Matt Pitkin On

Another option to go with the other answers is to use the built-in pathlib module and the touch() function (as in this answer), e.g.,

from pathlib import Path

...

self._dir = Path(tempfile.mkdtemp())
self._dir = self._dir / "test"
self._dir.mkdir()
self.checkpoint = self._dir / "file.txt"

# touch, i.e., create the file
self.checkpoint.touch()
0
SIGHUP On

You do not create "file.txt". All you have is a path to a non-existent file.

You also need to make sure you clean up your temporary directory.

import tempfile
import shutil
from pathlib import Path

class MyClass:
    def __init__(self):
        # create "test" directory within a temporary directory
        self.temp = Path(tempfile.mkdtemp())
        self._dir = self.temp / "test"
        self._dir.mkdir()
        # create empty "file.txt"
        self.checkpoint = self._dir / "file.txt"
        with open(self.checkpoint, "w"):
            pass
    def __del__(self):
        # don't forget to clean up
        shutil.rmtree(self.temp)