Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 卸载特定目录中的特定文件并解释任何错误情况?_Python_List_Function_Os.walk_Os.path - Fatal编程技术网

Python 卸载特定目录中的特定文件并解释任何错误情况?

Python 卸载特定目录中的特定文件并解释任何错误情况?,python,list,function,os.walk,os.path,Python,List,Function,Os.walk,Os.path,我试图减少以下代码,并可能创建一个可以重用到untar文件的函数。目前它做了以下工作: 遍历一个目录并查找当前年份和月份(YYMM*)“where*是不重要的”并包含特定文件(例如file.tar)的文件夹 测试文件夹和所需的tar文件,查看它是否具有被阻止的特定读/写权限,如果是,则生成一个.txt文件作为日志记录的形式,并且不允许重复引用锁定的文件 对于未锁定(读/写被拒绝)且包含我要查找的特定文件(例如file.tar)的文件,请取消对该文件的加载,并将内容保留在原始文件夹中 卸载完成后,

我试图减少以下代码,并可能创建一个可以重用到untar文件的函数。目前它做了以下工作:

  • 遍历一个目录并查找当前年份和月份(YYMM*)“where*是不重要的”并包含特定文件(例如file.tar)的文件夹
  • 测试文件夹和所需的tar文件,查看它是否具有被阻止的特定读/写权限,如果是,则生成一个.txt文件作为日志记录的形式,并且不允许重复引用锁定的文件
  • 对于未锁定(读/写被拒绝)且包含我要查找的特定文件(例如file.tar)的文件,请取消对该文件的加载,并将内容保留在原始文件夹中
  • 卸载完成后,删除tar文件并将tar文件内容保留在文件夹中
  • 目前,我唯一能想到的确定文件/文件夹是否被锁定的方法是通过硬代码值

    import os, re, tarfile
    from datetime import datetime
    dateTimeObj = datetime.now()
    curr = dateTimeObj.strftime('%y%m.')
    path = r'C:/Users/UserName/Documents/TestFolder/Folder/'
    Path_to_example_tarfile_parent_list = [] #Defines list for example specific folders
    RXList = []
    
    def oswalk_directory(your_path):
        for directory_path, subdirectories, files in os.walk(path):
            for each_folder_name in subdirectories:
                 #Add path+folder_name to end of each folder path
                for each_folder_name in subdirectories:
                    Path_to_example_tarfile_parent_list.append(path+each_folder_name)
                    #print (each_folder_name)
                    if re.search('example_Logs', each_folder_name) :#Traverse directories specific directories that have example_Logs folder
                        Path_to_example_tarfile_parent_list.append(path+each_folder_name)
    oswalk_directory(path)    
    #Create a list of directories to traverse in current year and month:
    print(os.getcwd())                           
    print (Path_to_example_tarfile_parent_list)           
    for i in range(len(Path_to_example_tarfile_parent_list)):
        #If a directory/folder has write permissions
        if(os.stat(Path_to_example_tarfile_parent_list[i]).st_mode == 16895):
            print("Checking file permissions RW = ok")
            
            for  directory_path, subdirectories, files in os.walk(Path_to_example_tarfile_parent_list[i]):       
                for each_folder_name in subdirectories:
                    print ("Just before checking for example_Logs")
                    if re.search('example_Logs', each_folder_name) :#Traverse directories specific directories that have example_Logs folder
                        isFile = False
                        print("If is not a file check")
                        print("Print path to file")
                        print (os.path.abspath(each_folder_name))
                        print(each_folder_name)
                        RXList.append((directory_path+'/'+each_folder_name).replace("\\","/")) #Append new list of folders to traverse, replace double slashes with single
                        isFile = os.path.isfile(directory_path+'/'+each_folder_name+'/example.tar')#Check if file exists in path
    
                        if isFile == True:
                            print("If is a file check")
                            if(os.stat(directory_path+'/'+each_folder_name+'/example.tar').st_mode == 33206):#Permissions for tar/archive file
                                #print (tarfile.info(root+'/'+each_folder_name+'/example.tar'))
                                print("Open tar file")
                                print(directory_path)
    
                                print(directory_path+'/'+each_folder_name+'/')
                                t = tarfile.open(directory_path+'/'+each_folder_name+'/')
                                for filename in ['example.tar']:
                                    try:
                                        f = t.extractfile(filename)
                                    except KeyError:
                                        print("Did not find tar filename")
                                    else:
                                        print("Found file")
                                #tarfile.extract(directory_path+'/'+each_folder_name+'/')
                                #tarfile.extractfile(directory_path+'/'+each_folder_name+'/') #extract tar file contents to folder
    
                                tarfile.close()
                                print("Close tar file after extraction")
                                #os.remove(directory_path+'/'+name+'/example.tar')
                            elif(os.stat(directory_path+'/'+each_folder_name+'/example.tar').st_mode == 33060): #Else if: no write permissions, break
                                print("Break if file is not writeable")
                                break
                        else:#else, there is no example tar file
                            break
                                                      
        #If a directory has write permissions are denied                    
        if(os.stat(Path_to_example_tarfile_parent_list[i]).st_mode == 16749):
            print("If directory has write permissions denied then proceed to opening text file")
            found=False#Set found (duplicate indicator) to false prior to loop
            #Check to see if No_Write_Permission_Folder exists to store files with denied permissions 
            isFile = os.path.isfile(path+'tmp/No_Write_Permission_To_SIL_Folder'+curr+'txt')
            if isFile == False:
              f=open(path+'tmp/No_Write_Permission_To_Folder'+curr+'txt','w+')
              f.close
            else:
                with open(path+'tmp/No_Write_Permission_To_example_Folder'+curr+'txt', 'r') as Readfile:
                    for line in Readfile:#For each line in txt file
    
                        if re.search(Path_to_example_tarfile_parent_list[i], line): #If current folder matches current line in txt file
                            found=True #Set found (duplicate) to True, matching line found in txt file 
                            break #terminate from inner loop
                    if found == False:
                        with open(path+'tmp/No_Write_Permission_To_example_Folder'+curr+'txt', 'a') as no_write_file:
                            no_write_file.seek(0,0) #Set cursor to beginning of file to allow line-by-line printing 
                            no_write_file.write(Path_to_example_tarfile_parent_list[i]+'\n'.replace("\\","/"))
    f = open(path+'/start_script.txt', 'a')
    f.close()
    

    对于“被拒绝”的文件,请使用
    set
    来存储文件路径,而不是文件路径。您可以在最后写入一个文件,或者在收集了一百万个目录之后写入,但您可能不需要这样做

    my_set={not_allowed_tweep'}
    my_set.add('not_allowed_twitter')
    my_set.add('this_is_罚款')
    我的电视机
    
    要获得单个函数,请使用递归函数进行遍历,而不是遍历一次,然后循环-尽管将逻辑适当地拆分为多个合适的函数,然后将此代码作为带有单个函数接口(如
    untar_tree()
    )的包使用可能更为优雅。。。 这是你的递归步行器:

    导入操作系统
    def WACK_it(文件夹):
    如果os.path.isdir(文件夹):
    对于os.listdir()中的f:
    如果os.path.isfile(f):
    #在此处执行逻辑(文件是否可写,如果不可写,请将其添加到集合中)
    印刷品(f)
    elif os.path.isdir(f):
    对于os.listdir(f)中的f2:
    #在此处执行逻辑(文件夹是否可写,如果不可写,请将其添加到另一个集合)
    打印(“继续行走”+f2)
    步行(f2)
    

    不要担心硬编码文件权限,它们不会在您的系统上更改。您可以使用
    stat.filemode(mode)
    将权限转换为
    -rwxrwx
    字符串,这样可以更容易地了解正在发生的事情。

    对于“被拒绝”的文件,请使用
    设置
    来存储文件路径,而不是文件。您可以在最后写入一个文件,或者在收集了一百万个目录之后写入,但您可能不需要这样做

    my_set={not_allowed_tweep'}
    my_set.add('not_allowed_twitter')
    my_set.add('this_is_罚款')
    我的电视机
    
    要获得单个函数,请使用递归函数进行遍历,而不是遍历一次,然后循环-尽管将逻辑适当地拆分为多个合适的函数,然后将此代码作为带有单个函数接口(如
    untar_tree()
    )的包使用可能更为优雅。。。 这是你的递归步行器:

    导入操作系统
    def WACK_it(文件夹):
    如果os.path.isdir(文件夹):
    对于os.listdir()中的f:
    如果os.path.isfile(f):
    #在此处执行逻辑(文件是否可写,如果不可写,请将其添加到集合中)
    印刷品(f)
    elif os.path.isdir(f):
    对于os.listdir(f)中的f2:
    #在此处执行逻辑(文件夹是否可写,如果不可写,请将其添加到另一个集合)
    打印(“继续行走”+f2)
    步行(f2)
    

    不要担心硬编码文件权限,它们不会在您的系统上更改。您可以使用
    stat.filemode(mode)
    将权限转换为
    -rwxrwx
    字符串,这样可以更轻松地了解正在发生的事情。

    下面是bash中的一个解决方案。我已经将您的需求作为注释标记了脚本。我已经测试了这个脚本,效果很好

    #/bin/bash
    # 1. 遍历目录并查找当前年份的文件夹和
    #月份(YYMM*)“where*是不关心的”,并包含一个特定的文件(例如file.tar)
    FILENAME=“file.tar”
    在读取f时查找-type f-iname“${FILENAME}”-newermt“$(日期'+%Y-%m-')1”
    做
    DIR=$(dirname“${F}”)
    # 2. 测试文件夹和所需的tar文件,查看它是否具有被阻止的特定读/写权限(如果有)
    #生成一个.txt文件作为日志记录的一种形式,并且不允许重复引用锁定的文件
    如果stat-c%A“$DIR”| grep-q“drw.rw.rw.”和&stat-c%A“$F”| grep-q“rw.rw.rw.”
    然后
    # 3. 与未锁定(读/写被拒绝)且包含我要访问的特定文件的文件
    #查找(例如file.tar),卸载文件并将内容保留在原始文件夹中
    tar-xvf“$F”-C“$DIR”
    # 4. 卸载完成后,删除tar文件并将tar文件内容保留在文件夹中
    rm-f“$f”
    其他的
    触摸“$F”\u lock.txt
    fi
    完成
    
    我不确定有两件事是我在阅读你的问题时没有收集到的:

  • 您希望筛选哪些所有者/组/公共权限?我假设
    -rw-rw-
  • tar归档文件是压缩为tar.gz还是压缩为tar文件?如果它们可以是
    .gz
    格式,我们必须更改
    tar-xvf“$F”-C“$DIR”
    行,以包含
    -z
    标志

  • 下面是bash中的一个解决方案。我已经将您的需求作为注释标记了脚本。我已经测试了这个脚本,效果很好

    #/bin/bash
    # 1. 遍历目录并查找当前年份的文件夹和
    #月份(YYMM*)“where*是不关心的”,并包含一个特定的文件(例如file.tar)
    FILENAME=“file.tar”
    在读取f时查找-type f-iname“${FILENAME}”-newermt“$(日期'+%Y-%m-')1”
    做
    DIR=$(dirname“${F}”)
    # 2. 测试文件夹和所需的tar文件,查看它是否具有被阻止的特定读/写权限(如果有)
    #生成一个.txt文件作为日志记录的形式,不允许重复引用