【发布时间】:2021-02-17 17:14:47
【问题描述】:
我正在尝试减少以下代码,并可能创建一个可重复用于解压缩文件的函数。目前它执行以下操作:
- 遍历目录并查看属于当前年份和月份 (YYMM*)“其中 * 不关心”并包含特定文件(例如 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()
【问题讨论】:
-
不清楚你在问什么。您是否要求人们总体上缩小您的代码?您是在问如何更好地检查 r/w 权限吗?您只是要求人们调试您的代码吗?
-
一般缩小。目录遍历的硬编码,以及权限读写测试,错误案例测试。
-
因为我在这方面不像大多数 Python 那样经验丰富
-
这听起来像 bash 脚本可能会更好。 Python 是必需的吗?如果是这样,您会接受使用
subprocess调用bash 脚本的python 答案吗? -
当你提到你想检查
if it has specific read/writing privileges blocked...你能在Linux Permissions和Owner/Group的上下文中重新表述一下吗i> / 公开 ?该权限组需要读写还是可以?
标签: python list function os.walk os.path