Verify a path in Python - python

I have to write a program in Python that receive a root path from command line. I parsed the given arguments with argparse module. Now, I have to check if the given path contains 2 folders. If not, I have to make a join between the actual path and those folders.
For example, I have the given_path="C:\Users\user\Downloads" and I want to verify if the given_path contains the folders "\documents\doc", after "..\Downloads" .
Also, the given_path differs from one input to another, but the 2 folders are always the same.
def main():
ap=argparse.ArgumentParser()
ap.add_argument("-i","--input_file", required=True, help="Root project path")
args=vars(ap.parse_args())
auxPath=args['input_file'].replace("\\","/")
if not os.path.exists(auxPath):
path=os.path.join(auxPath, 'documents/doc')
else:
path=auxPath
add_line(path) #add a text line into the specifix file
I tried to use os.path.exists(), but it does not do the right thing.
Thanks in advance for your help!

The proper way to check for the folder existence is:
os.path.isdir( os.path.join( root, folder))
because os.path.exists() will return True for the simple file as well.

Related

list of name and path of files in a directory and subdirectory where one or more subdir have a point in the middle python

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()]

How to get path to file while the name of file is not full in python

I'll try to describe the problem in a simple way.
I have a .txt file that I can not know the full name of it which located under constant path
[for example: the full name is: Hello_stack.txt, I only can give to function the part: 'Hello_']
the input is: Path_to_file/ + 'Hello_'
the expected output is: Path_to_file/Hello_stack.txt
How can i do that?
I tried to give a path and check recursively if part of my file name is exist and if so, to return it's path.
this is my implementation: [of course I'd like to get another way if it works]
def get_CS_R2M_METRO_CALLBACK_FILE_PATH():
directory = 'path_of_file'
file_name = directory + 'part_of_file_name'
const_path = Path(file_name)
for path in [p for p in const_path.rglob("*")]:
if path.is_file():
return path
Thanks for help.
You might retrieve the file list in your path and then select from the list based upon your partial file name. Here is a snippet of code to perform that type of function on a Linux machine.
import os
dir = '/home/craig/Python_Programs/GetFile'
files = os.listdir(dir)
print('Files--> ', files)
for i in files:
myfile = 'Hello_'
if (myfile[0:4] == i[0:4]):
print('File(s) like \"Hello_\"-->', i)
When I executed this simple program over a directory/folder that had various files in the directory, here was the output to the terminal.
Una:~/Python_Programs/GetFile$ python3 GetFile.py
Files--> ['Hello_Stack.txt', 'Okay.txt', 'Hi_Stack.txt', 'GetFile.py', 'Hello_Stack.bak']
File(s) like "Hello_"--> Hello_Stack.txt
File(s) like "Hello_"--> Hello_Stack.bak
The literal value for your path would be different on a Windows machine. I hope this might provide you with a method to achieve your goal.
Regards.

Moving files to a folder in python

I have a code that locates files in a folder for me by name and moves them to another set path.
import os, shutil
files = os.listdir("D:/Python/Test")
one = "one"
two = "two"
oney = "fold1"
twoy="fold2"
def findfile(x,y):
for file in files:
if x in file.lower():
while x in file.lower():
src = ('D:/Python/Test/'+''.join(file))
dest = ('D:/Python/Test/'+y)
if not os.path.exists(dest):
os.makedirs(dest)
shutil.move(src,dest)
break
findfile(one,oney)
findfile(two,twoy)
In this case, this program moves all the files in the Test folder to another path depending on the name, let's say one as an example:
If there is a .png named one, it will move it to the fold1 folder. The problem is that my code does not distinguish between types of files and what I would like is that it excludes the folders from the search.
If there is a folder called one, don't move it to the fold1 folder, only move it if it is a folder! The other files if you have to move them.
The files in the folder contain the string one, they are not called exactly that.
I don't know if I have explained myself very well, if something is not clear leave me a comment and I will try to explain it better!
Thanks in advance for your help!
os.path.isdir(path)
os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True.
Check with that function before.
Home this helps :)

How to open a specific path with open()?

I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.

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

Categories