os.path.join gives incorrect output in certain cases - python-3.x

I want to merge two paths using os.path.join() function. Paths I want to merge are- '/Users/Tushar/Desktop/' and '/Exp'.
I was doing - os.path.join('/Users/Tushar/Desktop','/Exp') and
Expected output was - '/Users/Tushar/Desktop/Exp'
But I actually got - '/Exp'
Why am I getting this output?
This kind of output is occurring on all systems, macOS, Windows, Linux
I have tried-
os.path.join('/Users/Tushar/Desktop','Exp') and I got the correct output i.e '/Users/Tushar/Desktop/Exp'
os.path.join('/Users/Tushar/Desktop/','Exp') and I got the correct output again i.e '/Users/Tushar/Desktop/Exp'
os.path.join('/Users/Tushar/Desktop','/Exp','/123') gives '/123' but I expected '/Users/Tushar/Desktop/Exp/123'
Apparently os.path.join('/Users/Tushar/Desktop/,'\\Exp') gives the correct output i.e. '/Users/Tushar/Desktop/\\Exp' where as os.path.join('/Users/Tushar/Desktop/','/Exp') gives the incorrect output '/Exp' .
So far, I have got to the point that it has something to do with the slash (/) at the end of '/Exp' which is the cause of this incorrect output.

From Python documentation
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
You'll need to manually strip all leading slashes in all components except the first one:
def my_join(root, *args):
args = [arg.lstrip(os.path.sep) for arg in args]
return os.path.join(root, *args)
See example:
>>> my_join('/home/ibug', '/oh', '/yeah', '/handsome')
'/home/ibug/oh/yeah/handsome'

this behavior is exactly as documented
If a component is an absolute path, all previous components are thrown
away and joining continues from the absolute path component.

Related

Why do we write dots (.) in path.resolve()?

The code shown below are examples used to explain path.resolve() on https://nodejs.org/api/path.html
path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
I noticed that all dots are just omited.
./baz is converted to baz in the first example.
../gif/image.gif is converted to /gif/image.gif in the 3rd example.
Then, why bother writing these dots?
What would happen if these dots didn't exist in the two examples?
Thx!
The path.resolve() method is used to resolve a sequence of path-segments to an absolute path.
It works by processing the sequence of paths from right to left, prepending each of the paths until the absolute path is created. The resulting path is normalized and trailing slashes are removed as required.
If no path segments are given as parameters, then the absolute path of the current working directory is used.
The passed argument is a series of file paths that would be resolved together to form an absolute path.

invalid syntax with shutil library

I want to try using this shutil.copy and my files got some symbolic characters inside its name, so I need to use this shutil.copy(src, dst, *, follow_symlinks=True) command. but the compiler keeps giving me the invalid syntax messages. I had google and didn't find any solution yet for this. anyone can point out what is wrong with my syntax? because I already tried to print out the files inside those directories and it is okay, the network shared folder also got the permission and so on. but don't know what is wrong with my syntax. help me. thanks
This is my current script
and here is the output I got
File "C:\Users\1000266946\Desktop\sa\we.py", line 17
shutil.copy( files, parse_destination_path, * , follow_symlinks = True)
^
SyntaxError: invalid syntax
[Finished in 0.3s]
first of all: the asterisk as you show it can be used in function definitions to define keyword-only arguments (see e.g. here) - but you don't use it in a function call. So in shutil.copy(src, dst, *, follow_symlinks=True) in the docs, it tells you that follow_symlinks can only be used as a keyword argument, not as a positional argument.
second: take a look at the return value of os.listdir(). it returns only file names, without the path as noted in the docs. shutil.copy() however expects a full path, not only the filename. so what you could do is
for file in parse_source_file_list:
shutil.copy(os.path.join(parse_source_path, file), os.path.join(parse_destination_path, file))
further reading: you might also be interested in having a look at glob and pathlib for file handling purposes (docs here and here).

Multiple image names

I need to save images after cropping that image in a for loop, how can this be achieved?
I have tried using img2.save("img"+i+".png") but this gives an error.
for file in files(path):
if file.endswith('.png'):
img=Image.open(file)
img2 = img.crop((x0,y0,x1,y1))
img2.save("img"+i+".png")
i+=1
The output should be as follows:
1. image1_crop.png
2. image2_crop.png
....
You forgot to post the exact error message but you obviously have a TypeError here:
img2.save("img"+i+".png")
since adding strings and numbers is not allowed (for the obvious reason that it makes no sense at all).
You want to use string formating instead:
img2.save("img{}.png".format(i))

Node.js path.join() ignoring parameter

According to the documentation:
The path.join() method joins all given path segments together using
the platform-specific separator as a delimiter, then normalizes the
resulting path.
Zero-length path segments are ignored. If the joined path string is a
zero-length string then '.' will be returned, representing the current
working directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'
path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'
A TypeError is thrown if any of the path segments is not a string.
Am I missing something? Why is:
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'
Ignoring 'quux' and '..' ?
They're are not zero length?
Even played around in the REPL (see screenshot)
Path.join isn't ignoring the last two parameters. Path.join takes the parameters you input and outputs a normalized path in string format.
So what's actually going on here is that it's constructing your string to form a path left to right, /foo/bar/baz/asdf/quux/, and the last parameter (..) is instructing path.join to 'go back a directory'. So your final result will be: /foo/bar/baz/asdf/
Part 1: what do you expect to happen when you provide an object instead of a string? To cut it short: It doesn’t make sense and hence doesn’t work.
Part 2: since .. means „up one directory“, this clears the last part of the path, hence it seems to not have any effect. Actually, it doesn’t get ignored - it’s just that the last two parameters clear each other.
With regard to path.join('foo', {}, 'bar');, {} represents an empty object, not a string (empty or not). Therefore, it is an invalid parameter for path.join().
With regard to path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');, .. refers to a parent directory.
Through experimentation in a terminal, you will find that...
/foo/bar/baz/asdf/quux/.. is equivalent to /foo/bar/baz/asdf

what does paper.path() with no arguments mean?

Im sure of paper.path("path string") .But some examples use path method with no arguments.
I looked into the docs paper.path, its saying the path string is optional, but it hasn't said what happens when there is no path string.
You're correct that it allows empty paths. The definition from W3C is:
svg-path:
wsp* moveto-drawto-command-groups? wsp*
allowing any amount of white space surrounding zero or one of the moveto/drawto command groups.
From that W3C documentation page:
Note that the BNF allows the path ‘d’ attribute to be empty. This is not an error, instead it disables rendering of the path.
In other words, it's a path with no elements in it. Without this, you'd probably have to have some kludge like m 0 0 if you wanted a path to do nothing.

Resources