-1

I'm trying to make a directory with a file in it

# lines 1-5
import logging, os

unix_doc_loc = '~\\byeStore'
win32_doc_loc = 'C:\\byeStore'

[...]
# line 108
class Store():
[...]
# lines 132-148
    def CacheCatalogue():
        import sys, os, time, platform, json
        byelogs.debug('sys, os and time were imported')
        # catalogue = Store.GetCatalogue() # commented out as this isn't functional yet
        catalogue = '{"lastUpdated": 1}'
        catalogue = json.loads(catalogue)
        byelogs.info('Catalogue recieved.')
        byelogs.debug(catalogue)
        if sys.platform == 'win32':
            byelogs.info('Detected Windows ({}). Using "C:\\byeStore\\"...'.format(sys.platform)) # line 142 - the troublesome line
            catcache = open('C:\\byeStore\\catalogue-cache.json', 'wt')
            byelogs.debug('Opened catcache')
        if catalogue['lastUpdated'] >= catcache['lastUpdated']:
            byelogs.info('Catalouge in cache is old. Updating...')
            catcache.write(catalogue)
            byelogs.info('Updated.')
            

Here's my terminal output

Z:\ByeStore\ByeStoreLibs>featuretest.py
Traceback (most recent call last):
  File "Z:\ByeStore\ByeStoreLibs\featuretest.py", line 5, in <module>
    byestore.Store.CacheCatalogue()
  File "Z:\ByeStore\ByeStoreLibs\src\byestore\__init__.py", line 142, in CacheCatalogue
    catcache = open('C:\\byeStore\\catalogue-cache.json', 'wt')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\byeStore\\catalogue-cache.json'

Z:\ByeStore\ByeStoreLibs>

I remember that the 'wt' part in open(file, 'wt') makes files. I even tried using "x", but that just didn't work, either. I just can't make the files for some reason.

My files are on GitHub, if you want the full source.

ByeMC
  • 15
  • 3
  • The `'w'` mode creates *files*, but not *directories*... Are you sure the full path up-to the file actually exists? – Tomerikoo Jun 20 '21 at 19:16
  • I tried `os.mkdir()` as well, forgot to mention that – ByeMC Jun 20 '21 at 19:17
  • Again, `mkdir` only creates the directory, i.e. the *last part* of the path. You need `mkdirs` to make sure it creates the *whole* path – Tomerikoo Jun 20 '21 at 19:18
  • See [How can I safely create a nested directory in Python?](https://stackoverflow.com/q/273192/6045800) – Tomerikoo Jun 20 '21 at 19:18

1 Answers1

1
from pathlib import Path

d = "C:\\byeStore\\"
Path(d).mkdir(parents=True, exist_ok=True)
open(d + "catalogue-cache.json", 'w+')

Couple things here:

  1. Create the directory first.
  2. 'w' is used for creating the file if it does not exist, not 't'.
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28