I like pathlib in python, just copying that library for simple path stuff in ahk. Allowing to do simple shortcuts like:
Code: Select all
Msgbox Path(A_ScriptDir).parent()
;prints dir above the script dir
global __file__ is more for memes and muscle memory
Msgbox Path(__file__).exists()
Its been years but from memory, emptying a file, or removing a file is best done with a filemove overwrite process.
Path(A_ScriptDir "\log.txt").remove() ; moves to temp before deleting
Path(A_ScriptDir "\log.txt").empty() ; appends empty str to temp with matching name before overwrite move
For part in Path(__file__).parts()
; array of path parts
Read and write quickly. I may remember wrong, but i/o with a fileopen object is faster, and this is just a shortcut.
Msgbox Path(A_ScriptDir "\log.txt").read()
If you need a method list its here https://github.com/samfisherirl/pathlib.ahk/blob/main/README.md
Probably forgetting a lot of stuff, will take feedback. I put this together in an hour, let me know of any errors.
Cheers.
Code: Select all
global __file__ := A_ScriptFullPath
class Path
{
__New(pathStr)
{
this.path := pathStr
this.cwd := A_WorkingDir
}
exists() => FileExist(this.path)
read() => FileOpen(this.path, "r").Read()
write(str) => FileOpen(this.path, "w").Write(str)
parent()
{
SplitPath(this.path, , &parentPath)
return parentPath
}
parts()
{
if InStr(this.path, "//")
{
delim := "//"
}
else if InStr(this.path, "/")
{
delim := "/"
}
else if InStr(this.path, "\\")
{
delim := "\\"
}
else if InStr(this.path, "\")
{
delim := "\"
}
return StrSplit(this.path, delim)
}
name()
{
SplitPath(this.path, &name)
return name
}
ext()
{
SplitPath(this.path, , , &ext)
return ext
}
empty()
{
if FileExist(this.path)
{
temp := A_Temp . "\" . this.name()
FileOpen(temp, "a").Write("")
FileMove(temp, this.path, 1)
}
}
remove()
{
temp := A_Temp . "\" . this.name()
if FileExist(this.path)
{
FileMove(this.path, temp, 1)
FileDelete(temp)
}
else if DirExist(this.path)
{
DirMove(this.path, temp, 1)
DirDelete(temp)
}
}
}