问题
I want to construct an absolute path with '.zip' in the end, Following is the snippet,
path='folder/file'
absPath=os.path.join('E:/',path,'.zip')
I am getting the following output for this,
E:/folder1/file\.zip
Required output,
E:/folder/file.zip
How can I avoid the \ before .zip while concatenating??
回答1:
Are you building paths for windows? Seemingly so because you use a drive letter at the start and because os.path.join is using backslashes to build the path. If so, you are going to have problems because you are using forward slashes in your input path.
os.path.join() works by taking the arguments provided and putting the proper separator between them. If you call .zip as an argument it will get a seperator before it which isn't what you want. What you probably want to say is this:
# folder1 and folder2 are presumably variables you are bringing in
abspath = os.path.join('E:\\', folder1, folder2 + '.zip')
If you go your way, or the way recommended in some answers, then you might as well just concatenate the strings together. If you actually want the path to show as "E:/folder1/folder2.zip" and folder1 and folder2 are known, you can easily do:
abspath = "E:/{0}/{1}.zip".format(folder1,folder2)
The only thing os.path.join does for you is put in the correct path separator for the OS you are running on. If you don't want that functionality, using it to concatenate a string is just unnecessary overhead.
回答2:
I would recommend you to avoid calling that folder2 a folder :) seems its the filename, and you add the .zip to that. I would do something like this
import os
dir_base="E:/"
dir_name='folder1'
base_filename='folder2'
filename_suffix = 'zip'
os.path.join(dir_base + dir_name, base_filename + "." + filename_suffix)
回答3:
While joining one or more paths, os.path.join will add one directory separator to each arguments it takes. For more Refer docs
As zip is not a directory it should include with the file name. Hence, string concatenation should be good instead of os.path.join
Updated code looks like this:
import os
path='folder1/folder2'
absPath=os.path.join('E:/',path+'.zip')
print(absPath)
OR
import os
path='folder1/folder2.zip'
absPath=os.path.join('E:/',path)
print(absPath)
There are lot of ways to write this!
来源:https://stackoverflow.com/questions/50975677/backslash-removal-while-constructing-absolute-path