I have a path to a file and a path to a directory. The file is supposed to be somewhere (multiple levels) in that directory. I want to compare the beginning of the path to the file with the path to the directory. So what I basically do is:
if file_path.startswith(directory_path):
do_something()
Both paths are strings. Unfortunately, my path to the file includes ".." and ".". So it looks something like this: /home/user/documents/folder/../pictures/house.jpg. As the other path does not contain those dots, the comparison fails, obviously. Is there a way in python to remove those spots from the string? I thought of using path.join() from the os module, which did not work.
Thanks a lot for any help :)
Is there a way in python to remove those spots from the string? I thought of using path.join() from the os module, which did not work. Thanks a lot for any help :)
os.path.abspath will normalise the path and absolutify it. Alternatively, pathlib.Path.resolve().
Related
I'm trying to get path and filename, from a directory, including those ones inside the subdirectories. The problem is that some subfolders have one or more points in the name.
So when I execute this code
listaFile=glob.glob('c:\test\ID_1'+/**/*.*',recursive= True)
I get
c:\test\ID_1\fil.e1.txt
c:\test\ID_1\fil.e2.doc
c:\test\ID_1\subfolder1\file1.txt
c:\test\ID_1\sub.folder2 (instead of c:\test\ID_1\sub.folder2\file1.txt)
thank you all in advance!
You need to filter it out checking if it's a file or folder. An easy way would be to use the pathlib instead of glob directly. Example below.
listaFile = [str(path) for path in pathlib.Path(r"c:\test\ID_1").rglob("*.*") if path.is_file()]
I'm writing some python code to generate the relative path. Situation need to be considered:
Under the same folder. I want "." or ".\", both of tham are ok for me.
Other folder. I want like ".\xxx\" and "..\xxx\xxx\"
os.path.relpath() will generate the relative path, but without .\ at the beginning and \ in the end. We can add \ in the end by using os.path.join(dirname, ""). But i can't figure out how to add ".\" at the beginning without impacting the first case when they are under the same folder and "..\xxx\xxx\".
It will give you relative path
import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir,'Path')
The relpath() function will produce the ".." syntax given the appropriate base to start from (second parameter). For instance, supposing you were writing something like a script generator that produces code using relative paths, if the working directory is as the second parameter to relpath() as below indicates, and you want to reference in your code another file in your project under a directory one level up and two deep, you'll get "../blah/blah".. In the case where you want to prefix paths in the same folder, you can simply do a join with ".". That will produce a path with the correct OS specific separator.
print(os.path.relpath("/foo/bar/blah/blah", "/foo/bar/baz"))
>>> ../blah/blah
print(os.path.join('.', 'blah'))
>>> ./blah
I am currently trying to go into a folder and call a python 2 script, but I cannot get any answer to go into a folder without using its full path. As example in DOS I would normally type this:
C:\unknownpath\> cd otherpath
C:\unknownpath\otherpath\>
Thanks for any help.
Try this:
import os
os.chdir('otherpath')
This at least matches your DOS example, and will change your working directory to otherpath relative to the directory the command is run from. For example if you are in /home/myusername/, then this will take you to /home/myusername/otherpath/. You can also use . for the current directory or .. to move back one directory. So if you are in /home/myusername/Desktop/, os.chdir('..') would change the working directory to /home/myusername/ and os.chdir('../Documents/ would change you to /home/myusername/Documents/, etc.
Forgive my use of Unix-style paths, but you should be able to easily translate these commands to Windows paths if that is the platform you are on. I don't want to attempt to use Windows paths in my examples because I won't be able to test their efficacy.
os.chdir works on relative path.
>>> os.getcwd()
'C:\\Users\\sba001\\PycharmProjects'
>>> os.listdir('.')
['untitled', 'untitled1', 'untitled2', 'untitled3', 'untitled4', 'untitled5']
>>> os.chdir('untitled')
>>> os.getcwd()
'C:\\Users\\sba001\\PycharmProjects\\untitled'
I'm trying to copy dir1 to dir2. Dir1 contains sub-folders and files. In the moment of copy I'm creating url like this C:/dirA/dir1 and C:/dirB/dir2. As you see all slashes are forwarded. When run I get this error
No such file or directory path C:/dirB/dir2\\folder1\\file.txt
As you see sub-folder and file have backslashes. I really do not know how to change that backslashes because when I create a paths I don't know the names of sub-folders/files. I can't post entire code because it's huge.
To copy I use distutils.dir_util.copy_tree.
It looks like you can use os.path.normpath on parts of your path to normalize them for current OS before you concatenate, on Windows it'll use correct slashes.
I have some homework that I am trying to complete. I don't want the answer. I'm just having trouble in starting. The work I have tried is not working at all... Can someone please just provide a push in the right direction. I am trying to learn but after trying and trying I need some help.
I know I can you os.path.basename() to get the basename and then add it to the file name but I can't get it together.
Here is the assignment
In this project, write a function that takes a directory path and creates an archive of the directory only. For example, if the same path were used as in the example ("c:\\xxxx\\Archives\\archive_me"), the zipfile would contain archive_me\\groucho, archive_me\\harpo and archive_me\\chico.
The base directory (archive_me in the example above) is the final element of the input, and all paths recorded in the zipfile should start with the base directory.
If the directory contains sub-directories, the sub-directory names and any files in the sub-directories should not be included. (Hint: You can use isfile() to determine if a filename represents a regular file and not a directory.)
Thanks again any direction would be great.
It would help to know what you tried yourself, so I'm only giving a few pointers to methods in the standard libraries:
os.listdir to get the a list of files and folders under a given directory (beware, it returns only the file/folder name, not the full path!)
os.path.isfile as mentioned in the assignment to check if a given path represents a file or a folder
os.path.isdir, the opposite of os.path.isfile (thanks inspectorG4adget)
os.path.join to join a filename with the basedir without having to worry about slashes and delimiters
ZipFile for handling, well, zip files
zipFile.write to write the files found to the zip
I'm not sure you'll need all of those, but it doesn't hurt knowing they exist.