Get folder name from list of string - groovy

I have a list of a hundred folders like below:
C:\Mother\Son\foler_A\a_file.txt
C:\Mother\Son\foler_A\foler_B\a_file.txt
C:\Mother\Son\foler_B\a_file.txt
C:\Mother\Son\foler_C\foler_D\a_file.txt
...
Can someone help me to get the list of the lastest folder level like:
['folder_A', [folder_B], [folder_B],[folder_D]]

If these files actually exist on your system, you could do:
def parents = folders.collect { new File(it).parentFile?.name }
If not, you could do:
def parents = folders*.split( '\\\\' )*.getAt(-2)

Related

How can I append a folder directory with many sub directories to a QTreeView using QStandardItemModel in PyQt6

I am building a script that takes a path and gets the folders. Then appends those folder names as items to another item that I am calling "Root". I am using QStandardItemModel and not QFileSystemModel because I intend to replace "Root" with a name that the user will provide and I am using QTreeView as a preview to the entire structure of the folder.
Current issue:
I would like to add the entire directory and include the sub directories but have it all appended under "Root". In my attempt below I am only getting the first set of folder.
In this example, I created a folder, with many sub folders and am trying to add those folders in correct order to my "Root" item.
import os
from PyQt6.QtWidgets import QApplication, QTreeView
from PyQt6.QtGui import QStandardItemModel, QStandardItem
app = QApplication([])
# Create the model
model = QStandardItemModel()
# Set the path to the directory containing the folders you want to add to the tree view
path = r"replace\with\path\to\folder"
# Create an Item for everything to parent under
root_item = QStandardItem("Root")
model.appendRow(root_item)
#iterate through the directory provided
for index,(root, folders, files) in enumerate(os.walk(path)):
folder_root_name = (str(root))
folder_root_name = folder_root_name.split('\\')[-1]
for folder in folders:
folder_item = QStandardItem(folder)
if index == 0:
root_item.appendRow(folder_item)
else:
folder_root_name_item = QStandardItem(folder_root_name)
folder_root_name_item.appendRow(folder_item)
tree_view = QTreeView()
tree_view.setModel(model)
tree_view.show()
app.exec()
Here is a photo of what I am trying to accomplish:
Whenever you have to deal with tree/directory structures, you have to consider that you're using a 3-dimensional model, which automatically calls for a recursive behavior.
While, normally, such a structure would require a relative 3D "model" as a reference, a basic string-based dictionary can suffice with a simple directory-based model.
The assumption is based on the fact that os.walk will always walk through sub directories, even if they are empty.
The trick is to use a dictionary that has keys as full directory paths, and items as their values.
root_item = QStandardItem("Root")
parents = {path: root_item}
model.appendRow(root_item)
def getParent(path):
parent = parents.get(path)
if parent:
return parent
grandParentPath, parentName = path.rsplit(os.sep, 1)
parent = QStandardItem(parentName)
parents[path] = parent
getParent(grandParentPath).appendRow(parent)
return parent
for root, folders, files in os.walk(path):
getParent(root)

How to print the directory which is 1 level up in groovy?

May I know how to print the directory path which is 1 level up? (eg. the groovy file is located in "abc/def/ghi/dummy.groovy" and I want to get the "abc/def" path)
here is my dummy.groovy script
File fileCon= new File("/../")
logger.debug((String.format("[%s]", fileCon))
groovy file could be loaded from plain file, from jar, from url.
i'd not recommend to use this approach - it will not work for all cases.
def url = this.getClass().getProtectionDomain().getCodeSource()?.getLocation()
println new URL(url, '..')
Here is how you get the parent directory as File:
def file = new File('abc/def/ghi/dummy.groovy')
println "Parent: ${file.getParentFile().absolutePath}"
it will give you abc/def/ghi/. You may get parent folder from the result:
println "Parent: ${file.getParentFile().getParentFile().absolutePath}"
you'll get your desired abc/def.
I didn't see any File in GroovyDocs, so I presume this is a Java Class.
So why not just use:
def file = new File('abc/def/ghi/dummy.groovy')
def filePath = file.getParent().getParent()

Creating automatic folder and files in soapui

I wrote a groovy script in soapui to create files in certain location in my pc. How can I make it dynamic and enable the user to write the location the files are saved to by write the location in configuration file imported at test suite level.
if(context.expand('${#Project#ProduceReports}') == 'true') {
def resultDir = new File("D:\\Reports");
if(!resultDir.exists()) {
resultDir.mkdirs();
}
def resultsFile = new File(resultDir, "CSVReport.csv");
}
If you want to get the path from a testSuite property, you can do it as you do with the project property, using context.expand:
def yourPath = context.expand('${#TestSuite#pathDirectory}')
Or alternatively you can do the same with:
def yourPath = context.testCase.testSuite.getPropertyValue('pathDirectory')
Maybe this is out of scope for your question, but could be helpful. If you need you can also use UISupport to ask the user to enter the path he wants with the follow code:
def ui = com.eviware.soapui.support.UISupport;
// the prompt question, title, and default value
def path = ui.prompt("Enter the path","Title","/base/path");
log.info path
This shows:
Define project level custom property REPORT_PATH with value D:/Reports/CSVReport.csv i.e., full path including file and path separate by / slash even on windows platform.
Then use the below script to write the data.
//Define the content that goes as report file. Of course, you may change the content as need by you
def content = """Name,Result
Test1,passed
Test2,failed"""
//Read the project property where path is configured
def reportFileName = context.expand('${#Project#REPORT_PATH}')
//Create file object for reports
def reportFile = new File(reportFileName)
//Create parent directories if does not exists
if (!reportFile.parentFile.exists()) {
reportFile.parentFile.mkdirs()
}
//Write the content into file
reportFile.write(content)

How to get files by using index of List files in groovy

I got the List of all files by using but it give all files , I need specific files from list.
import groovy.io.FileType
def list = []
def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
list.each {
println it.path
}
The method File.eachFileRecurse(FileType, Closure) can only filter by FileType; the options being FILES, DIRECTORIES, and ANY (everything). Keep in mind this is file type in the filesystem sense, and has nothing to do with the file contents. For instance, an HTML document and a PNG image are both FILES.
If you want to filter by, say, the file extension, you can use File.traverse(Map, Closure):
import groovy.io.FileType
def list = []
def dir = new File("source")
dir.traverse(type: FileType.FILES, nameFilter: ~/.*\.html/) { list << it }
list.each {
println it.path
}
In the example above, I used the nameFilter option to specify a regular expression to filter the file name by. You can about the other available options in the documentation.

How to display Folders and recent items

I have 2 questions in trying to retrieve a set of data from a directory and displays it out into the ListWidget.
As I am a linux user, I set my ListWidget to read my directory from Desktop in which insides contains say 5 folders and 5 misc items (.txt, .py etc)
Currently I am trying to make my ListWidget to display just the folders but apparently it does that but it also displays all the items, making it a total of 10 items instead of 5.
I tried looking up on the net but I am unable to find any info. Can someone help me?
Pertaining to Qns 1, I am wondering if it is possible to display the top 3 recent folders in the ListWidget, if a checkbox is being checked?
import glob
import os
def test(object):
testList = QListWidget()
localDir = os.listdir("/u/ykt/Desktop/test")
testList.addItems(localDir)
Maybe you should try "QFileDialog" like the following:
class MyWidget(QDialog):
def __init__(self):
QDialog.__init__(self)
fileNames = QFileDialog.getExistingDirectory(self, "list dir", "C:\\",QFileDialog.ShowDirsOnly)
print fileNames
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
app.exec_()
2nd question, you could reference to this: enter link description here
I guess that you are expecting that os.listdir() will return only the directory names from the given path. Actually it returns the file names too. If you want to add only directories to the listWidget, do the following:
import os
osp = os.path
def test(object):
testList = QListWidget()
dirPath = "/u/ykt/Desktop/test"
localDir = os.listdir(dirPath)
for dir in lacalDir:
path = osp.join(dirPath, dir)
if osp.isdir(path):
testList.addItem(dir)
This will add only directories to the listWidget ignoring the files.
If you want to get the access time for the files and/or folders, use time following method:
import os.path as osp
accessTime = osp.getatime("path/to/dir") # returns the timestamp
Get access time for all the directories and one which has the greatest value is the latest accessed directory. This way you can get the latest accessed 3 directories.

Resources