Groovy split path into name and parent - groovy

I am trying to split a path into parent and the name.
When trying
String path = "/root/file"
File file = new File(path)
println("Name: " + file.name)
println("Parent: " + file.parent)
We get
Name: file
Parent: /root
With the Windows path C:\\root\\file.exe we get
Name: C:\root\file.exe
Parent: null
Is this the intended behaviour? And if it is how do I get the same result for a Windows path? (If possible please without using regular expressions)

use .replace to change the "\" to "/
String path = "C:\\root\\file.exe"
path = path.replace("\\","/")
File file = new File(path)
println("Name: " + file.name)
println("Parent: " + file.parent)

Related

How to concatenate strings in python

I'm trying to run a command in Python by concatenating two strings, each string has an absolute path in it. It's throwing an error. Below is the code and error for reference. Kindly correct me where am I going wrong.
Code:
def test_execute_resources_temp_dir(self):
sourcePath = Path("Gemini_logo.png").absolute()
print(sourcePath)
with tempfile.TemporaryDirectory() as tmpdirname:
destination = Path(tmpdirname).resolve("Gemini_logo_converted.jpg")
print('created temporary directory', destination)
command = "magick convert" + sourcePath +" "+ destination
formatConversion = FormatConversion()
formatConversion.executeCommand(command)
Error:
TypeError: can only concatenate str (not "WindowsPath") to str test_FormatConversion.py:65: TypeError
You can replace sourcePath with str(sourcePath).
Similarly, you can replace destination with str(destination)
command = "magick convert" + str(sourcePath) +" "+ str(destination)
This worked out for me
def test_execute_resources_temp_dir(self):
os.chdir('..')
sourcePath = Path("src\\resources\\Gemini_logo.png").absolute()
print(sourcePath)
with tempfile.TemporaryDirectory() as tmpdirname:
# os.mkdir(os.path.basename(tmpdirname))
destination = Path(tmpdirname+"/Gemini_logo_converted1.jpg")
print('created temporary directory', destination)
command = **"magick convert"+" "+ str(sourcePath) + " " + str(destination)**

image processing commands in python using for loop

I have this part code which i don't understand the for loop part:
also what does file path holds and how it is different than all file path?
all_files_path = glob.glob("ADNI1_Screening_1.5T/ADNI/*/*/*/*/*.nii")
for file_path in all_file_path:
print(os.system("./runROBEX.sh " + file_path + " stripped/" +file_path.split("/")[-1]))

How to get the name of the directory from the name of the directory + the file

In an application, I can get the path to a file which resides in a directory as a string:
"/path/to/the/file.txt"
In order to write another another file into that same directory, I want to change the string "/path/to/the/file.txt" and remove the part "file.txt" to finally only get
"/path/to/the/"
as a string
I could use
string = "/path/to/the/file.txt"
string.split('/')
and then glue all the term (except the last one) together with a loop
Is there an easy way to do it?
You can use os.path.basename for getting last part of path and delete it with using replace.
import os
path = "/path/to/the/file.txt"
delete = os.path.basename(os.path.normpath(path))
print(delete) # will return file.txt
#Remove file.txt in path
path = path.replace(delete,'')
print(path)
OUTPUT :
file.txt
/path/to/the/
Let say you have an array include txt files . you can get all path like
new_path = ['file2.txt','file3.txt','file4.txt']
for get_new_path in new_path:
print(path + get_new_path)
OUTPUT :
/path/to/the/file2.txt
/path/to/the/file3.txt
/path/to/the/file4.txt
Here is what I finally used
iter = len(string.split('/'))-1
directory_path_str = ""
for i in range(0,iter):
directory_path_str = directory_path_str + srtr.split('/')[i] + "/"

Unable to execute child_process.exec() when path has spaces

I am using appjs * and I want to execute a command to open a folder.
What I have
var path = __dirname + '/folder to open/';
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);
Error
Could not find file C:\Program
What I tried
I already tried to escape the spaces, that didn't work.
var path = __dirname + '/folder to open/';
path = path.replace(' ', '\ ');
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);
When I put the path between quotes, No folder is opened, only another prompt.
var path = "\"" + __dirname + "/folder to open/\"";
path = path.replace(' ', '\ ');
// path = "C:\Program Files\myapplication/folder to open/"
require("child_process").exec("start " + path);
Related bug https://github.com/isaacs/npm/pull/2479
Does anyone has a fix or a workaround?
* link removed
To open a path than contains spaces, you must replace with a double backslash.
In your code you escaped the space character:
"\ "
What you need to do is escape the backslash character so it makes it into the output string:
"\\ "
Try this:
var path = __dirname + '/folder to open/';
// Notice the double-backslashes on this following line
path = path.replace(/ /g, '\\ ');
require("child_process").exec("start " + path);
Well, I fixed it.
Or something like it.
Instead of using
"start " + path
I used
"%SystemRoot%\\explorer.exe \"" + path + "\""
Notice the quotes and the forward slashes.
In my case it is fixed by adding double quotes for the path except the first drive name or letter.
import * as path from 'path'; // npm module
const filePath = 'C:/Program Files/my application/file to open/test.txt';
const rootName = path.parse(filePath).root; // "C:/"
const filePathTo = `${rootName}"${filePath.replace(rootName, '')}"`; // C:/"Program Files/my application/file to open/test.txt"
require("child_process").exec(`start ${filePathTo}`);
The text file will be opened.
this works for me
f= file.replace(/ /g,"\\\ ")
You can also use the old-style 8-character-max/no-space names for each path.
The one I always used was always coding c:\PROGRA~1 instead of c:\Program Files, although this only works on english systems.
If the first 8 characters of any path with more chars are unique, I expect you can do something like newPath = origPath.sub(/\W/g, '').substr(0, 6) + "~1"
Don't have a windows system here, just going by memory.

Script to rename and copy files to a new directory.

Hi I have recently made this script to rename files I scan for work with a prefix and a date. It works pretty well however it would be great if it could make a directory in the current directory with the same name as the first file then move all the scanned files there. E.g. First file is renamed to 'Scanned As At 22-03-2012 0' then a directory called 'Scanned As At 22-03-2012 0' (Path being M:\Claire\Scanned As At 22-03-2012 0) is made and that file is placed in there.
I'm having a hard time figuring out the best way to do this. Thanks in advance!
import os
import datetime
#target = input( 'Enter full directory path: ')
#prefix = input( 'Enter prefix: ')
target = 'M://Claire//'
prefix = 'Scanned As At '
os.chdir(target)
allfiles = os.listdir(target)
count = 0
for filename in allfiles:
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
os.rename(filename, prefix + x + " "+str(count) +".pdf")
count +=1
Not quite clear about your requirement. If not rename the file, only put it under the directory, then you can use the following codes (only the for-loop of your example):
for filename in allfiles:
if not os.isfile(filename): continue
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
dirname = prefix + x + " " + str(count)
target = os.path.join(dirname, filename)
os.renames(filename, target)
count +=1
You can check help(os.renames).

Resources