Split directory path with another path
pathlib split path
python split path by directories
python re split path
python directory path
python get directory from path
python get first directory in path
powershell get folder name from path
I read the directory path using system properties in java which will work both in windows and Linux based systems. Now I need to split this path with only a portion of the path to retrieve the rest. eg.,
I need to split the above path with
C:\Test1\Test2 and retrieve
When I get this as string and use
split function that will give me error as illegal character because of
"\" character. If I plan to escape this character with
"\\", this may not work in Linux box. Is there a way I can make this work both in Linux and Windows?
Use the below approach.
//Windows String s = "C:\\Test1\\Test2\\Test3\\Test4"; String output = s.split(("/".equals(File.separator))? File.separator : "\\\\" ); //output: [C:, Test1, Test2, Test3, Test4] //Linux: String linuxString = "/Test1/Test2/Test3/Test4"; String linuxOutput = linuxString.split(("/".equals(File.separator))? File.separator : "\\\\" ); //output: [, Test1, Test2, Test3, Test4]
Hope this will solve the issue.
Split-Path, How do I get the path of a directory in Python? The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path. Examples. Example 1: Get the qualifier of a path
You are looking for
File.separator. Use it to split your string.
From the docs,
The system-dependent default name-separator character, represented as a string for convenience.
Python, of the running script file can be obtained with __file__ . Syntax: os.path.split(path) Parameter: path: A path-like object representing a file system path. A path-like object is either a str or bytes object representing a path. Return Type: This method returns a tuple that represents head and tail of the specified path name.
The pattern passed to
String.split has the regular expression syntax, thus the
java.util.regex package is the place to look for additional tools for dealing with them, like quoting a string to enforce literal matching.
So a solution only using system properties and string operations would look like
String path=System.getProperty("your.property"), sep=System.getProperty("file.separator"); for(String s: path.split(Pattern.quote(sep))) System.out.println(s);
However, there is no reason not to use the dedicated APIs:
Path path = Paths.get(System.getProperty("your.property")); if(path.isAbsolute()) System.out.println(path.getRoot()); for(Path p: path) System.out.println(p);
Note that this also handles root paths correctly, i.e. on Windows, the root of a drive is like
C:, and on Linux, the root is
/, not an empty string, and both cases are not handled correctly when just splitting at the separator chars.
Even before Java 7, there was an API that could handle this:
File path = new File(System.getProperty("your.property")); for(File f = path; f != null; f = f.getParentFile()) System.out.println(f.getName().isEmpty()? f.getPath(): f.getName());
though the code will iterate the elements in the opposite order.
Note, how simple your specific task of splitting at two levels above the path becomes with the dedicated API:
Path path = Paths.get(System.getProperty("your.property")); Path first = path.getParent().getParent(), second = first.relativize(path); System.out.println("first: "+first); System.out.println("second: "+second);
Get the path of running file (.py) in Python: __file, of that location varies by version of Windows and whether or not you are using folder redirection. folders =  while 1: path, folder = os.path.split(path) if folder != "": folders.append(folder) else: if path != "": folders.append(path) break folders.reverse() (This pops a "\" at the start of folders if the path was originally absolute. You could lose a bit of code if you didn't want that.)
You can use separator when you are building a file path.
about_Modules, We can define a function that uses os.path.split to break out all of the parts of a file or directory path: import os, sys def splitall(path): allparts =  while 1: parts In the above example, for simplicity, we have shown only 4 components in the PATH variable. However, in a real-time environment, the number of components in a PATH variable could be really lot. And hence it becomes really cumbersome to interpret OR to know whether a particular component in the PATH variable what we are looking for is present or
Splitting a Path into All of Its Parts, path.split() method. OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This ) to indicate the current path.) -Resolve Display the items that are referenced by the resulting split path instead of displaying the path elements. -Credential PSCredential Use a credential to validate access to the file.
11.2. os.path — Common pathname manipulations, Unlike a unix shell, Python does not do any automatic path expansions. This is the second element of the pair returned by passing path to the function split(). Return the directory name of pathname path. This is Return True if pathname path is a mount point: a point in a file system where a different file system has been cd c:\test\folder A for %X in (*)do echo %~nxX (Note that special files like desktop.ini will not show up.) It's also possible to redirect the output to a file using >>: cd c:\test\folder A for %X in (*)do echo %~nxX>>c:\test\output.txt. For a real example, assuming you want to robocopy all files from folder-A to folder-B (non-recursively):
10.1. os.path — Common pathname manipulations, Unlike a unix shell, Python does not do any automatic path expansions. This is the second element of the pair returned by passing path to the function split(). Return the directory name of pathname path. This is Return True if pathname path is a mount point: a point in a file system where a different file system has been Get-Content-Path. \ file.lst | Split-Path – Leaf # Reads the contents from file.lst and extracts the file name from each line. Split-Path isn’t just restricted to the file system; it can also be applied to the registry and the AD (read Mount Active Directory as a drive in PowerShell ).
- Have you considered using interface Path ?
- I have updated the answer, Please check. you can add a check the separator an based on the separator you can use the split.
- You borrowed
File.separatorfrom my answer. Anyways, +1 for the implementation pain though! :)
- @Sohail, this is going to return me a array or splits. Rather I want is a whole string as Test3/Test4. May be like the main path being split with C:/Test1/Test2 which I will be knowing. This final output may be like ["C:/Test1/Test2","Test3/Test4"]
- @RaghavendraBankapur, if you know the first part then you can use somthing like this.
String s = "C:\\Test1\\Test2\\Test3\\Test4"; String output = new String; output = s.substring(0, s.indexOf("Test2")); output = s.substring(s.indexOf("Test2") + 6, s.length()); System.out.println(Arrays.toString(output));
- @Sohail this is more like indexing. If the values are going to be static it works fine. But when the values are going to be dynamic this may fail. I could achieve it by
String details= f.getAbsolutePath().substring(f.getAbsolutePath().length()- (f.getAbsolutePath().length()-System.getProperty("path").length()));The above is going to give me 2 items in array. This worked both in Linux and windows.
- this is going to give me 2nd portion of the path but split with individual parts. Ultimately I wanted was only 2 parts.
- Did you read the entire answer, especially the last part?
secondare exactly two parts and if this operation doesn’t match your intention, you should edit your question to describe, what you actually want.
- I did read your full answer. You solution will work if I know how deep I can penetrate with the parent. If this comes as a user input into my program then it will difficult. Keeping this option dynamic I commented that it may not work if my inputs are dynamic and not known. Anyways thank you for your answer.
- That’s why I said, you should edit your question to describe, what you actually want. You received several answers telling you how to split at every separator. You keep telling that you don’t want that. You said, you want to split into two parts, which, given your example input, would be split at a certain depth. If that’s not the criteria, you should specify the actual criteria. On the other hand, if the
firstpart is known, like hinted in one of your comments, just ignore the
.getParent().getParent()operation and focus on the
second = first.relativize(path)solution to get the second.