2016-12-19 1 views
0

J'ai un script pour rechercher les répertoires créés il y a 3 mois (dans OperDir), et pour les répertoires créés il y a un an (DelDir). Il prend des noms de répertoire et crée des fichiers .txt avec ces noms de répertoire. Cela fonctionne correctement sous Windows, mais ne crée pas de fichiers sous Linux, même sous la racine. Pourrait-il être un problème avec les autorisations ou autre chose? Voici le code:Le script Python ne crée pas de fichier texte sous Linux

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/****") 

Je suis désolé si c'est une question stupide, je suis nouveau en Python.

Merci pour votre aide.

+3

Bienvenue dans Stack Overflow! Pour vous aider à obtenir une réponse, pourriez-vous essayer de restreindre votre code au plus petit échantillon reproduisant votre erreur? S'il vous plaît lire [Comment créer un MCVE] (http://stackoverflow.com/help/mcve) pour plus de détails sur la façon de poser une bonne question. – JETM

+1

Vous pouvez également être intéressé de savoir que les objets datetime ont des attributs comme year, month, day, ainsi votre fonction dateCheck pourrait éviter tous ces appels 'int (str())' et se référer simplement à 'operDate.month',' operDate. year', et checkTime pourrait juste se référer à 'curr_time = time.gmtime(); curr_time.tm_year' –

+0

Quel message d'erreur obtenez-vous? Veuillez toujours inclure le message d'erreur complet à vos questions. – pts

Répondre

1

La réponse courte est que c'est votre utilisation de caractères génériques (et en fait, trop de caractères génériques):

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

os.walk tente d'ouvrir un répertoire appelé /opt/***, qui n'existe pas. Si vous ouvrez /opt/ à la place, cela fonctionne. Cependant, il y a quelques problèmes avec le code, y compris ce qui se passe lorsque vous marchez sur une arborescence de répertoires lorsque vous le changez, et que vous n'utilisez pas non plus les attributs datetime pour rechercher le jour, le mois et l'année , mais au lieu de faire des conversions string et int et des tranches pour extraire l'information à la dure. Puis-je suggérer de publier le script sur https://codereview.stackexchange.com/questions/tagged/python, comme une expérience d'apprentissage?

Un exemple de ce que je veux dire par les datetime commentaires, cette fonction:

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) 

pourrait être remplacé par ce qui est beaucoup plus claire:

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) 

Ou même simplement passer le datetime objets autour et en regardant l'année, le mois et le jour où ils sont nécessaires:

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)  
+0

Merci. Cela sera très utile pour l'apprentissage ultérieur. Je vais poster le script sur CodeReview A propos du répertoire opt: la fonction dataCheck prend des arguments valides, je viens de le changer avec des symboles *. Argument est un chemin d'accès valide au répertoire existant. –