Python File Path Name - python

What is the difference between "./file_name", "../file_name" and "file_name"when used as the file path in Python?
For example, if you want to save in the file_path, is it correct that "../file_name" will save file_name inside the current directory? And "./file_name" will save it to the desktop? It's really confusing.

./file_name and file_name mean the same thing - a file called file_name in the current working directory.
../file_name means a file called file_name in the in the parent directory of the current working directory.
Summary
. represents current directory whereas .. represents parent directory.
Explanation by example
if the current working directory is this/that/folder then:
. results in this/that/folder
.. results in this/that
../.. results in this
.././../other results in this/other

Basically, ./ is the current directory, while ../ is the parent of the current directory. Both are actually hard links in filesystems, i.e., they are needed in order to specify relative paths.
Let's consider the following:
/root/
directory_a
directory_a_a
file_name
directory_a_b
file_name
directory_b
directory_b_a
directory_b_b
and let's consider your current working directory is /root/directory_a/directory_a_a. Then, from this directory if you refer to ./file_name you are referring to /root/directory_a/directory_a_a/file_name. On the other hand, if you refer to ../file_name you are referring to /root/directory_a/file_name.
In the end, ./ and ../ depend upon your current working directory. If you want to be very specific you should use an absolute path.

Related

Navigating directories

After getting the path to the current working directory using:
cwd = os.getcwd()
How would one go up one folder: C:/project/analysis/ to C:/project/ and enter a folder called data (C:/project/data/)?
In general it a bad idea to 'enter' a directory (ie change the current directory), unless that is explicity part of the behaviour of the program.
In general to open a file in one directory 'over from where you are you can do .. to navigate up one level.
In your case you can open a file using the path ../data/<filename> - in other words use relative file names.
If you really need to change the current working directory you can use os.chdir() but remember this could well have side effects - for example if you import modules from your local directory then using os.chdir() will probably impact that import.
As per Python documentation, you could try this:
os.chdir("../data")

How to find saved file in PyCharm

I have saved a file. I have not given a path to this. In the project folder, nowhere can I find the file.
Is there any method that will tell me where the default path is where the file has gone?
model_file = "test.h5"
model.save(model_file, overwrite=True)
print(os.getcwd()) will print the working directory, where relative paths start from (and where a relative filename such as foo.txt will end up in).

Python move files from current path to specific folder named like or similar to the file being moved

My Folder Structure looks like this:
Folder 95000
Folder 95002
Folder 95009
AR_95000.pdf
AR_95002.pdf
AR_95009.pdf
BS_95000.pdf
BS_95002.pdf
BS_95009.pdf
[Note folder is named 95000, 95002 etc, the actual word 'folder' is not present in folder name, its just mentioned here for representation purpose.]
My goal is, move files "AR_95000.pdf" and "BS_95000.pdf" to folder named - "95000",
then "AR_95002.pdf" and "BS_95002.pdf" to folder named - "95002"and so on.
The PDFs are reports generated by system and thus I can not control the naming of the same.
Thanks!
Using pathlib this task becomes super easy:
from pathlib import Path
root = Path("/path/to/your/root/dir")
for file in root.glob("*.pdf"):
folder_name = file.stem.rpartition("_")[-1]
file.rename(root / folder_name / file.name)
As you can see, one main advantage of pathlib over os/shutil (in this case) is the interface Path objects provide directly to os-like functions. This way the actual copying (rename()) is done directly as an instance method.
References:
Path.glob
Path.stem
str.rpartition
Path.rename
path concatenation

Python: Checking for directories in CVS Repository

I'm wondering if I could use
os.path.isdir(sourceDirectory)
to check for the existence of a directory in a CVS repository. Similarly, if the os.walk method would work for a repository directory. If not, what would be a good way to approach this problem?
os handles this very well already! Isn't python wonderful?
The following example searches for a file named CSV in the root directory of your machine, but you can point it to any directory you like, including a relative path.
def file_exists():
path = '/' # the path you want to search for the file in
target = 'CSV' # name of the directory
if target in os.list:
#do whatever you were going to do once you confirmed that this file exists
return True
return False

How to generate path of a directory in python

I have a file abc.py under the workspace dir.
I am using os.listdir('/home/workspace/tests') in abc.py to list all the files (test1.py, test2.py...)
I want to generate the path '/home/workspace/tests' or even '/home/workspace' instead of hardcoding it.
I tried os.getcwd() and os.path.dirname(os.path.abspath(____file____)) but this instead generates the path where the test script is being run.
How to go about it?
The only way you can refer to a specific folder from which you don't relate in any way and you don't want to hardcode it, is to pass it as a parameter to the script (search for: command line argument)
I think you are asking about how to get the relative path instead of absolute one.
Absolute path is the one like: "/home/workspace"
Relative looks like the following "./../workspace"
You should construct the relative path from the dir where your script is (/home/workspace/tests) to the dir that you want to acces (/home/workspace) that means, in this case, to go one step up in the directory tree.
You can get this by executing:
os.path.dirname(os.path.join("..", os.path.abspath(__file__)))
The same result may be achieved if you go two steps up and one step down to workspace dir:
os.path.dirname(os.path.join("..", "..", "workspace", os.path.abspath(__file__)))
In this manner you actually can access any directory without knowing it's absolute path, but only knowing where it resides relatively to your executed file.

Categories