How to delete all files in a directory? - directory

My script :
#RequireAdmin
FileDelete("C:\Users\Administrator\Desktop\temp\")
I want to delete all files in that directory. I also tried :
#RequireAdmin
DirRemove("C:\Users\Administrator\Desktop\temp\")
But it's not working, any suggestion?

The syntax for FileDelete() is FileDelete("filename") ;not only directory!. You can also use wildcards for filename (* and ?).
DirRemove() works as follows: DirRemove ( "path" [, recurse = 0] ). With recurse=0 (default), deletes the folder, but only if it is empty. With recurse=1 removes files and subdirectories (like the DOS DelTree command).
Maybe you misunderstood the flag to use:
; Remove only the empty folder "Folder_path"
DirRemove("Folder_Path")
; Remove folder "Folder_Path" with all subfolder and all files within
DirRemove("Folder_Path", 1)
If this doesn't work it's a matter of system rights. If you want to delete files without deleting containing folder:
#include <Files.au3>
; Get all files in folder and delete them:
Local $aFilesInRoot = _FileListToArray("Your_Path", 1, True) ; 1=$FLTA_FILES = Return files only, True=returns full path
For $i = 1 To $aFilesInRoot[0]
FileDelete($aFilesInRoot[1])
Next
; Get all subfolders under root and delete them:
Local $aFolderInRoot = _FileListToArray("Your_Path", 2, True) ;2=$FLTA_FOLDERS = Return Folders only
For $i = 1 To $aFolderInRoot[0]
DirRemove($aFolderInRoot[1], 1)
Next
But isn't it easier to remake the deleted folder after deleting all with only one command?

Related

Copy/move files by folder name pattern in R

I have a folder (~/PATH/MYFOLDER) with a lot of subfolders and files.
Subfolders are named, for example, as: LClass_orgx, LClass_orgy, LClass_phyw, LClass_detz, LClass_appq
Inside each subfolder has a lot of image files (*.png and/or *.jpg)
In ~/PATH/ I have folders with part of the name of subfolders, as: orgx, orgy, phyw, detz, appq
I would to copy image files of subfolders: LClass_orgx, LClass_orgy, LClass_phyw, LClass_detz, LClass_appq, to respective folders: orgx, orgy, phyw, detz, appq
Any help would be great.
Thanks all.
You can use sub to remove "MYFOLDER/Lclass_" from the file names. Something like this:
from = list.files(
path = "~/PATH/MYFOLDER",
pattern = "(png|jpg)$",
recursive = TRUE,
full.names = TRUE
)
to = sub(x = from, pattern = "MYFOLDER/Lclass_", replacement = "", fixed = TRUE)
file.copy(from = from, to = to)
This should take input from list.files like "~/PATH/MYFOLDER/LClass_orgx/file.jpg" (from) and change it to "~/PATH/orgx/file.jpg" (to), and then copy it accordingly. You could then use file.remove to delete the old ones. (Potentially you could do this all at once with file.rename, but it seems safer to copy and take a minute to check that things look right before deleting the old ones.)
If you need to be more specific in the sources, you could modify the list.files(pattern) to specify the source directories you mention, LClass_orgx, LClass_orgy, LClass_phyw, LClass_detz, LClass_appq.

Passing parameter as variable in Run function

as the title says, here is my code but its not working
; Get the parameter from open file dialog
GUICtrlSetData($locationtxt, FileOpenDialog("Select the program", '', "Supported files (*.exe;*.msi;*.reg;*.inf)|Executable Files (*.exe)|Microsoft Installer files (*.msi)|Registry files (*.reg)|Inf files (*.inf)", 3))
; store the value in a variable
$abc = GUICtrlRead($locationtxt)
; Run the program and pass the parameter value
Run("ussf.exe " & $abc )
; If i do it this way, its working but i want the parameter value from the open dialog not fixed
Run("ussf.exe C:\Users\project\ccsetup563.exe")
The second parameter for Run() is the working directory, not an argument for the program. I think you should be using ShellExecute(), or ShellExecuteWait() instead.

Workaround for case-sensitive input to dir

I am using Octave 5.1.0 on Windows 10 (x64). I am parsing a series of directories looking for an Excel spreadsheet in each directory with "logbook" in its filename. The problem is these files are created by hand and the filenaming isn't consistent: sometimes it's "LogBook", other times it's "logbook", etc...
It looks like the string passed as input to the dir function is case-sensitive so if I don't have the correct case, dir returns an empty struct. Currently, I am using the following workaround, but I wondered if there was a better way of doing this (for a start I haven't captured all possible upper/lower case combinations):
logbook = dir('*LogBook.xls*');
if isempty(logbook)
logbook = dir('*logbook.xls*');
if isempty(logbook)
logbook = dir('*Logbook.xls*');
if isempty(logbook)
logbook = dir('*logBook.xls*');
if isempty(logbook)
error(['Could not find logbook spreadsheet in ' dir_name '.'])
end
end
end
end
You need to get the list of filenames (either via readdir, dir, ls), and then search for the string in that list. If you use readdir, it can be done like this:
[files, err, msg] = readdir ('.'); # read current directory
if (err != 0)
error ("failed to readdir (error code %d): %s", msg);
endif
logbook_indices = find (cellfun (#any, regexpi (files, 'logbook'));
logbook_filenames = files(logbook_indices);
A much less standard approach could be:
glob ('*[lL][oO][gG][bB][oO][kK]*')

Create directory structure using template in a text file

Suppose I have a text file text.txt that contains several lines of text indented using single spaces (not tabs) like:
My folder1/
My folder2/
My folder3/
file1.md
My folder4/
For example, and actual directory template might look like:
Proposal/
rules/
proposal/
document.tex
figs/
tabs/
ref/
log/
src/
master.r
crdat/
andat/
temp/
data/
raw/
clean/
Admin/
budget/
contract/
invoices/
receipts/
team/
hiring/
vitae/
gantt/
forms/
misc/
Study/
document.tex
figs/
tabs/
ref/
log/
src/
master.r
crdat/
andat/
temp/
data/
raw/
clean/
Dissemination/
presentations/
conference1/
submission.md
slides.tex
notes.md
admin/
registration/
travel/
receipts/
program/
forms/
conference2/
manuscripts/
journal1/
submission/
letter_v1.tex
manuscript_v1.pdf
replication_v1.zip
comments/
reviewer1.txt
R&R/
letter_v2.tex
manuscript_v2.tex
diff.tex
replication_v2.zip
journal2/
master_notes.md
TODOs.md
README.md
Essentially the file is a template for directory structure. This template can be set by the user. She could use different templates for different projects say, and the names are generic. The only constraints are that hierarchy is established using spaces, and folders end in forward slash.
I want to write a function that takes a any such directory template as an input and creates a directory structure in your current working directory. The pseudo code is as follows:
lines <- readLines(text.txt)
last.indent <- 0
for (i in lines) {
Create directory structure by looking at leading character and last characters (folders end in /)
using dir.create(i) or file.create(i)
}
I suspect you're actually doing something more complicated. In which case this may not work:
library(qdap); library(reports)
x <- readLines(n=13) ## you'd read this in from a file I assume
My folder1/
My folder2/
My folder3/
file1.md
My folder4/
My folder1b/
My folder2/
My folder3/
file1.zip
My folder1c/
My folder2/
My folder3/
file1.pdf
## You didn't ask for this but this keeps the direcories contained
new <- folder(new)
setwd(new)
dirs <- which(substring(x, 1, 1) != " ")
lens <- lapply(seq_along(dirs), function(i) {
dirs[i]:c(tail(dirs - 1, -1), length(x))[i]
})
paths <- split(x, rep(1:length(dirs), sapply(lens, length)))
path <- sapply(paths, function(x) paste(Trim(x), collapse=""))
is.dir <- sapply(path, function(x) substring(x, nchar(x))) == "/"
lapply(seq_along(is.dir), function(i){
out <- folder(folder.name =ifelse(is.dir[i],
path[i], dirname(path[i])))
if(!is.dir[i]) {
cat("", file = paste0(path[i], "_hold_.txt"))
}
})

Why a directory string loss '/' will return the parent qdir in Qt

It maybe a bug. Please read webclectic answer.
If QFileInfo(filename) loss '/', QDir::absolutePath will return the parent string. Like below code.
QFileInfo file("e:/QtExample/mytest/out/res/res1/");
QFileInfo file_no("e:/QtExample/mytest/out/res/res1");
QDir dirFile = file.absoluteDir();
QDir dirFile_no = file_no.absoluteDir();
QString strDirFile = dirFile.absolutePath(); //"E:/QtExample/mytest/out/res/res1
QString strDirFile_no = dirFile_no.absolutePath(); //"E:/QtExample/mytest/out/res
I found it with my QTreeView. My code will call the slot from QTreeView::clicked signals
connect(ui.m_pView,SIGNAL(clicked(QModelIndex)),this,SLOT(myClicked(QModelIndex)));
the slot will get the QModelIndex, then I use QFileSystemMode::fileInfo get the QFileInfo.
QFileInfo rFileInfo = m_model.fileInfo(index);
QDir absDir = rFileInfoDir.absoluteDir();
But the return of QFileInfo always return "e:/QtExample/mytest/out/res/res", so If I call QFileInfo::absoluteDir get the directory, the directory is the parent of "res1".So I will get wrong entrylst from my hope directory.
Should I add the '/' after the absoluteFilePath() to get the right QDir?
And why strDirPath equal "E:/QtExample/mytest/out/res/res1", but rDir will list the "res" directory entrylist?
//rFileInfoDir == E:/QtExample/mytest/out/res/res1
QString strDirPath = rFileInfoDir.absoluteFilePath();
QDir rDir = rFileInfoDir.absoluteDir();
If you go deep into the absoluteDir() function call you will see why this happens. In Windows the fileName function in qfsfileengine_win.cpp is called. In this function there is this code part:
if (file == AbsolutePathName) {
int slash = ret.lastIndexOf(QLatin1Char('/'));
if (slash < 0)
return ret;
else if (ret.at(0) != QLatin1Char('/') && slash == 2)
return ret.left(3); // include the slash
else
return ret.left(slash > 0 ? slash : 1);
}
You can see that it returns the part of the string left of the last separator. I don't know if this is the desired behavior or a bug. Maybe you could issue a Qt bug for this. The documentation is not clear on this matter.
From the QFileInfo::absoluteDir() docs:
Returns the file's absolute path as a QDir object.
In the case of "/foo/bar", the file is "bar" and its directory is /foo. It doesn't matter if bar is a directory or a plain file, as directories are also files. If you want something like "for files, return the parent directory, for directories, return the directory itself", you'll have to write your own little function testing via QFileInfo::isDir for what to return.
e:/QtExample/mytest/out/res/res1/res is the path to a directory called "res", e:/QtExample/mytest/out/res/res1/ is the path to an empty directory (called ""). So whether you should add a slash or not depends on what you are trying to do.
In my own personal opinion it's better not to add a final slash because it's easy to add it if you need to, while removing it is not as straightforward.

Resources