I want to search a file in a tree.
I know the filename and the root of the tree, but I want to find the file path. I use python-3.4 on windows 7.
I have:
#I have a list with C header file name => my_headers_list that look like:
for part in my_headers_list:
print(part)
#show this
common.h
extern.h
something.h
else.h
I also have a tree ( something/ is a folder):
Software/
something.c
Component1/
extern.c
extern.h
Component2/
Core/
common.h
common.c
Config/
common_m.c
common_m.h
Component3/
Managment/
Core/
Config/
etc it's an example but it's really close of my real case.
I want:
#a list like the first one, but with the full path of the files
for part in my_headers_list:
print(part)
#show this
Software/Component2/Core/common.h
Software/Component1/extern.h
Software/Component3/Core/something.h
Software/Component3/Management/else.h
I precise that it should be generic, so I can't make hard link or hard path etc.
For the moment I've try some tricky scripts with some os.listdir etc but it seems messy and don't always work.
#I try something like this
dirs = os.listdir("Software/")
for part in dirs:
#don't know how to correctly manage these informations to get what I want.
Do you guys have some way to do this ?
Keep in mind that I don't want to add any lib or plugin to my python.
Thank you,
Regards,
Question resolved in comments.
I'll use os.walk / glob.
Thank to #kevin #Lafexlos
Related
I've written a program which uses tkinter's askdirectory to get a folder and then convert all images into another format. But I've noticed something weird.
The first step the program does is ask for a directory and then use os.walk to create a filelist, which the converter (in this case PILLOW for most images and psd-tools for photoshop images) then takes. This code looks something like this:
from tkinter import Tk
from tkinter.filedialog import askdirectory
import os
path = askdirectory(title='Select Folder')
all_files=[]
for root, _, files in os.walk(path):
for f in files:
all_files.append(os.path.join(root, f))
convert(all_files) #not important here
I've written a couple of little scripts that deal with files and paths, so I know how annoying this can be and how allergic some modules react to specific formats for paths. So, when I copy/paste a path into a script, i usually write path = r"path i copied from file explorer" and everything beyond that only happens with os.path.join(), which has worked perfectly until now.
I noticed strange filepaths in my error messages that claimed it couldn't find a file. So I printed my file lists out:
for line in all_files:
print(line)
And i got this:
G:/Downloads/New folder (2)\file1.png
G:/Downloads/New folder (2)\file2.png
G:/Downloads/New folder (2)\file3.png
G:/Downloads/New folder (2)\file4.png
...
It seems like tkinter formats the string weirdly (one forward slash instead of two backward slashes, which is the case when i copy/paste a dir into a rawString). And os.path.join() cannot understand tkinter paths properly as a result.
But what I don't understand is why it's happening here. Because as far as I see it, os.path.join joins not the input path by tkinter with a filename, but it joins the root provided by os.walk, which should be in a format os.path.join understands, because I never had any problems with it before this.
So my question would either be "How can I reformat the tkinter string, so that it gets properly understood as a directory path by os.path.join and os.walk?" or "Why does os.walk behave like this here and put the wrongly formatted directoy into the root variable?"
(I know i could probably just type path = path.replace("/", "\"), but A) i am not sure if there would be other subtle differences and B) i really am curious why this imo weird thing it happening, so I don't make a similar mistake again)
EDIT (SOLUTION): Thanks to chepners comment, I was able to fix it (they didn't make a proper 'answer', hence why I'm adding this here, so someone with a similar problem doesn't miss the solution). Replacing the line all_files.append(os.path.join(root, f)) by all_files.append(os.path.normpath(os.path.join(root, f))) solved it, since normpath can handle a mixture of / and \. The reason for this can he read in chepners comments, I'm not adding them here.
Hello I have a piece of code where I want to join a path with a picture name which I am getting from an excel file. The thing is that my code changes my path string.
src=os.path.join('C:\\Users\\ekrem\\Desktop\\Distributions\\16-17',ws.cell(row=cell.row,column=2).value)
print('src=',src)
so here my src variable should be something like this:
C:\Users\ekrem\Desktop\Distributions\16-17\26231043_1686575684735993_7548330554586169888_n.jpg
but as you see I printed the src variable and I got this
src= C:\Users\ekrem\Desktop\16-17\26231043_1686575684735993_7548330554586169888_n.jpg
here the distribution folder is missing, have you any idea why?
Thank you in advance
In this case assuming the end piece is always a single filename it might be easier to do this with f-strings. That way there is no path weirdness that happens something like this should work (Assuming you're on python 3.6+, if you aren't then do this instead):
src = f'C:\\Users\\ekrem\\Desktop\\Distributions\\16-17\\{ws.cell(row=cell.row,column=2).value}'
print(f'{source=}') # Print source with label
P.S I would recommend switching the C:\\Users\\<name> with %USERPROFILE% (so %USERPROFILE%\\Desktop\\Distributions\\16-17\\), that way if you change accounts or hard-drives this still works.
Then just do validation with:
if os.path.exists(src):
# Do stuff
else:
raise FileNotFoundError(f"{src} file could not be found")
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().
I have a little question, I have a directorie which contain directories (with files in it) and files. Can i use os.walk to treat files 1 by 1 but not the files into directories ?
Thank you for your answers
Do you want to only list the files in the highest level dir without going in to sub-dirs? os.listdir should do it for you.
You can easily add a check to skip dirs this way
for f in os.listdir(path):
if f.is_dir():
continue
print f
What about
os.walk("/path/to/dir").next()[2]
Well for exemple i have a directorie like that:
boite_noire/
.....helloworld/
.....test1.txt
.....test2.txt
I would like somethink like that at the end of the script:
boite_noire/
.....helloworld/
.....test1/
.....test2/
And in the test1 dirctorie I put test1.txt and same for test2.
I tried listdir but without success and yes os.walk.next()2 should be a good idea cause my problem is when i run my script my os.walk scan the directories and files inside and i don't want to, i only want him to scan the files at the source.
My code with os.walk
enter image description here
My code with os.listdir:
enter image description here
I think there is something easier for both but i don't know what :/
I want to do something like this.
import os
for root, dirs, files in os.walk("/mydir"):
print files
However, the directory I want to check is under My Network Places, and the path is "\blue01\syng\getem\BY", and python says that there is no such directory. Why can't python see this directory? Does it have something to do with the fact that is under My Network Places?
lets say for example, the python file is located on your desktop, it will be something like this:
c:\users\yourname\desktop\python_file.py
and your target is located at
\blue01\syng\getem\BY\mydir
inside of the python_file.py if you mention /mydir its going to first check the directory that its in ( which would be the desktop) and then its going to check your system path. ( learn how that stuff works because it will be useful later, but for now just forget about it)
since c:\users\yourname\desktop\ != \blue01\syng\getem\BY
its gonna have NO idea what you are talking about.
open a window and browse to your target directory, and then copy the address bar
on windows, if its in your network places, the entire path is gonna look something like:
\\someIPaddress_or_domain\some_form_of_directory_structure\blue01\syng\getem\BY\mydir
just paste that into python, put it in double quotes and put an r in front of it ( to avoid escaping charachters )
for root, dirs, files in os.walk(r"\\someIPaddress_or_domain\some_form_of_directory_structure\blue01\syng\getem\BY\mydir"):
So TL;DR put exact paths.