0

I am trying to create a code to create a directory based on content of several files. The files are stored in a folder, and I only want to open files that start with the letter "f", and in the files there are dates I want to read written in this format "YYY-MM-DD". The files should then be stored with the following new locations: YYYY/MM/DD. I have the following incomplete code, but I cannot get the MM directories to be created:

import os, testSystem, getpass

my_user_name = (getpass.getuser())
userPath = testSystem.switch_system()
ProjectPath = os.path.join('/Users', my_user_name, "Python_Data", "filesToSort")

year = []
month = []
day1 = []
for filereader in os.listdir(ProjectPath):
    os.chdir(ProjectPath)
    if filereader.startswith('f'):
        f = open(filereader, 'r')
        line = f.readline()
        line = line.split('-')
        year.append(line[0:3])
        month.append(line[4:5])
        day1.append(line[6:7])
        print(year)
        print(month)
        print(day1)
    for yearcheck in year:
        os.chdir(ProjectPath)
        if not os.path.exists(os.path.join(ProjectPath, yearcheck)):
            os.mkdir(yearcheck)
        for monthcheck in month:
            if year.index(yearcheck) == month.index(monthcheck) and not os.path.exists(os.path.join(ProjectPath, yearcheck, monthcheck)):
                os.chdir(yearcheck)
                os.mkdir(monthcheck)
    os.chdir(ProjectPath)

f.close()

Can somebody help?

1 Answers1

0

Check out this answer: https://stackoverflow.com/a/41146954/10761353

Instead of creating nested folders named YYY, then MM and finally DD, just create all 3 levels in one go.

Adam Smooch
  • 1,167
  • 1
  • 12
  • 27
  • I am only limited to use os module and cannot use makedirs – Talal Abbas Aug 08 '22 at 01:32
  • So this is homework? there's os.system("mkdir -p ") but sounds like your teacher wants you to implement your own `makedirs` then: breakdown the requested path, then add some `if`s and `for`s. – Adam Smooch Aug 08 '22 at 01:35