Python 脚本不会在 Linux 上创建文本文件

标签 python linux python-2.6

我有一个脚本来查找 3 个月前创建的目录(在 OperDir 中)和一年前创建的目录(DelDir)。它获取目录名并使用这些目录名创建一个 .txt 文件。它在 Windows 上工作正常,但在 Linux 上不创建文件,即使在 root 下也是如此。可能是权限问题还是其他问题?这是代码:

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

如果这是一个愚蠢的问题,我很抱歉,我是 Python 新手。

感谢您的帮助。

最佳答案

简短的回答是你使用了通配符(事实上,通配符太多了):

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

os.walk 尝试打开名为 /opt/*** 的目录,该目录不存在。如果您改为打开 /opt/,它会起作用。

然而,代码有很多问题,包括当您在目录树上移动时更改它时会发生什么,也没有使用 datetime 属性来查看日、月和年,而是进行字符串和整数转换和切片以艰难地提取信息。 我可以建议在 https://codereview.stackexchange.com/questions/tagged/python 上发布脚本吗?以及,作为一种学习经验?

我所说的 datetime 注释的一个例子,这个函数:

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

或者甚至只是传递 datetime 对象并在需要时查找年月日:

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)    

关于Python 脚本不会在 Linux 上创建文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41224654/

相关文章:

python - numpy genfromtxt 或 numpy loadtxt "ValueError: could not convert string to float"或 "too many values to unpack",几乎尝试了所有方法

python - scikit-learn 只允许使用线性 svms 访问 clf.coef_ 是有原因的吗?

linux - 计算列的中值,输出该值并说明是否为 "OK"或 "ERROR"(如果在可接受范围内或之外)

python - 按长度排序的列表,但在一个步骤中按字母顺序排列的长度相同

python - 如何在python中将集合转换为列表?

python - Python 中的守护线程与守护进程

python - 将 2D 元素的大列表转换为 3D NumPy 数组 - 内存问题

php - 限制访问我网站上的图像,除非通过我自己的 html

linux - 无法通过 Visual Studio 将调试器附加到 Azure Linux Web 服务

python - 将字符串转换为八进制数的最pythonic方式