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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am only limited to use os module and cannot use makedirs
So this is homework? there's os.system("mkdir -p <path>") but sounds like your teacher wants you to implement your own makedirs then: breakdown the requested path, then add some ifs and fors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.