0

I have a script to look for directories created 3 month ago (in OperDir), and for directories made a year ago (DelDir). It takes dirnames and creates a .txt files with these dirnames. It works correctly on Windows, but does not create files on Linux, even under the root. Could it be a problem with the permissions or something else? Here is the code:

import os, time, sys
from os.path import join, getsize, isfile, isdir, splitext
import ctypes
import platform
from os import path
import shutil
import logging
from logging import handlers
from datetime import datetime, timedelta

def checkTime(timed):                           
    curr_time = str(time.gmtime())
    year_st = curr_time.find('tm_year') + 8
    year_fin = curr_time.find('tm_mon') - 2
    year = int(curr_time[year_st:year_fin:1])
    month_st = curr_time.find('tm_mon') + 7
    month_fin = curr_time.find('tm_mday') - 2
    month = int(curr_time[month_st:month_fin:1])
    day_st = curr_time.find('tm_mday') + 8
    day_fin = curr_time.find('tm_hour') - 2
    day = int(curr_time[day_st:day_fin:1])
    if timed == 'year':
        return year
    elif timed == 'month':
        return month
    elif timed == 'day':
        return day

def split(path):
    head, tail = os.path.split(path)
    return tail

def moveFileOperativeTest(pathOper, pathDelete, nameOper):
    logfile = open('MovedFilesLog.txt', 'a+')
    logfile.write(str(checkTime('day')) + '.' + str(checkTime('month')) + '.' + str(checkTime('year')) + ' - ' + "File '%s' will be moved from '%s' to the '%s'.\n" % (nameOper, pathOper, pathDelete))
    logfile.close
    '''with open('MovedFilesLog.txt', 'a') as logfile:
        logfile.write(checkTime('day') + '.' + checkTime('month') + '.' + checkTime('year') + ' - ' + "File '%s' will be moved from '%s' to the '%s'.\n" % (nameOper, pathOper, pathDelete))
        logfile.close()'''

def removeFileTest(pathDelete, nameDelete):
    logfile = open('RemovedFilesLog.txt', 'a+')
    logfile.write(str(checkTime('day')) + '.' + str(checkTime('month')) + '.' + str(checkTime('year')) + ' - ' + "File '%s' will be removed from '%s' directory.\n" % (nameDelete, pathDelete))
    logfile.close
    '''with open('RemovedFilesLog.txt', 'a') as logfile:
        logfile.write(checkTime('day') + '.' + checkTime('month') + '.' + checkTime('year') + ' - ' + "File '%s' will be removed from '%s' directory.\n" % (nameDelete, pathDelete))
        logfile.close()'''

def pathed(pathOper, pathDelete, yearOper, monthOper, dayOper, yearDel, monthDel, dayDel):
    for dirname, dirnames, filenames in os.walk(pathOper):
        for subdirname in dirnames:
            dirpath = os.path.join(dirname, subdirname)
            if getCreationDate(dirpath, 'day') == dayOper and getCreationDate(dirpath, 'month') == monthOper and getCreationDate(dirpath, 'year') == yearOper:
                nameOper = split(dirpath)
                print "opername = " +nameOper
                moveFileOperativeTest(pathOper, pathDelete, nameOper)
                #moveFileOperative(pathOper, pathDelete, nameOper)
    for dirname, dirnames, filenames in os.walk(pathDelete):
        for subdirname in dirnames:
            dirpath = os.path.join(dirname, subdirname)
            if getCreationDate(dirpath, 'day') == dayOper and getCreationDate(dirpath, 'month') == monthOper and getCreationDate(dirpath, 'year') == yearOper:
                nameDelete = split(dirpath)
                print 'namedel = ' + nameDelete
                removeFileTest(pathDelete, nameDelete)
                #removeFile(pathDelete, nameDelete)
    print 'Done'

def dateCheck(pathOper, pathDelete):
    operVar = 92
    delVar = 365
    operDate = datetime.now() - timedelta(days=operVar)
    delDate = datetime.now() - timedelta(days=delVar)
    yearOper = int(str(operDate)[0:4:1])
    monthOper = int(str(operDate)[5:7:1])
    dayOper = int(str(operDate)[8:10:1])
    yearDel = int(str(delDate)[0:4:1])
    monthDel = int(str(delDate)[5:7:1])
    dayDel = int(str(delDate)[8:10:1])
    pathed(pathOper, pathDelete, yearOper, monthOper, dayOper, yearDel, monthDel, dayDel)

def getCreationDate(path, timed):
    dict_month = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
    creation = str(time.ctime(os.path.getctime(path)))
    month = int(dict_month.get(creation[4:7:1]))
    day = int(creation[8:10:1])
    year = int(creation[-4::1])
    if timed == 'day':
        return day
    elif timed == 'month':
        return month
    else:
        return year



dateCheck("/opt/***", "/opt/****")

I'm sorry if that's a silly question, I'm new in Python.

Thanks for your help.

4
  • 3
    Welcome to Stack Overflow! To make it easier for you to get an answer, could you please try to narrow down your code to the smallest sample that reproduces your error? Please read How to create a MCVE for more details on how to ask a good question. Commented Dec 19, 2016 at 14:25
  • 1
    You may also be interested to know that datetime objects have attributes like year, month, day, so your dateCheck function could avoid all those int(str()) calls and just refer to operDate.month, operDate.year, and checkTime could just refer to curr_time = time.gmtime(); curr_time.tm_year Commented Dec 19, 2016 at 14:35
  • What error message do you get? Please always include the entire error message to your questions. Commented Dec 19, 2016 at 15:03
  • To JETM: Thank you. And thanks for your correction. I'll edit it as soon as possible To Simon Fraser: Thank you too. That is really necessary info, I'll remmember that. To pts: There is no error message. That works correctly on Windows, but does nothing on Linux, just shows "Done" message Commented Dec 20, 2016 at 5:39

1 Answer 1

1

The short answer is that it's your use of wildcards (and in fact, too many wildcards):

dateCheck("/opt/***", "/opt/****")

os.walk tries to open a directory called /opt/***, which doesn't exist. If you open /opt/ instead, it works.

There are quite a few issues with the code, however, including what happens when you're walking over a directory tree when you're changing it, and also not using the datetime attributes to look up day, month and year, but instead doing string and int conversions and slices to extract the information the hard way. May I suggest posting the script on https://codereview.stackexchange.com/questions/tagged/python as well, as a learning experience?

An an example of what I mean by the datetime comments, this function:

def dateCheck(pathOper, pathDelete):
    operVar = 92
    delVar = 365
    operDate = datetime.now() - timedelta(days=operVar)
    delDate = datetime.now() - timedelta(days=delVar)
    yearOper = int(str(operDate)[0:4:1])
    monthOper = int(str(operDate)[5:7:1])
    dayOper = int(str(operDate)[8:10:1])
    yearDel = int(str(delDate)[0:4:1])
    monthDel = int(str(delDate)[5:7:1])
    dayDel = int(str(delDate)[8:10:1])
    pathed(pathOper, pathDelete, yearOper, monthOper, dayOper, yearDel, monthDel, dayDel)

Could be replaced with this, which is much clearer:

def dateCheck(pathOper, pathDelete):
    operVar = 92
    delVar = 365
    operDate = datetime.now() - timedelta(days=operVar)
    delDate = datetime.now() - timedelta(days=delVar)
    pathed(pathOper, pathDelete, operDate.year, operDate.month,
        operDate.day, delDate.year, delDate.month, delDate.day)

Or even just passing the datetime objects around and looking up the year, month and day when they're needed:

def dateCheck(pathOper, pathDelete):
    operVar = 92
    delVar = 365
    operDate = datetime.now() - timedelta(days=operVar)
    delDate = datetime.now() - timedelta(days=delVar)
    pathed(pathOper, pathDelete, operDate, delDate)    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That will be very helpful in further learning. I'll post the script on CodeReview About the opt directory: dataCheck function takes valid arguments, i've just changed it with * symbols. Argument is a valid path to the existing directory.

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.