File Path retrieving problem

M

music24by7

Hi all,

I am new to Python, i have installed python 2.5.4 and it is my
requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath("NEWS.txt") # here NEWS.txt exists and it shows the
path of the file as C:\Python25\WorkSpace\NEWS.txt
print realpath("abc.txt") # here abc.txt does not exist but still it
shows C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why????


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print "Not Found"
else:
print realpath(filename)

i have given the filename as "NEWS.txt" and "abc.txt" but i am always
getting the output as "Not Found"


Can anyone please tell me where am i doing wrong????

also any suggestions to retrieve the filepath from a given filename is
highly appreciated.

Thanks in advance.


Regards,
Sudhir
 
S

Steve Holden

Hi all,

I am new to Python, i have installed python 2.5.4 and it is my
requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath("NEWS.txt") # here NEWS.txt exists and it shows the
path of the file as C:\Python25\WorkSpace\NEWS.txt
print realpath("abc.txt") # here abc.txt does not exist but still it
shows C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why????


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print "Not Found"
else:
print realpath(filename)

i have given the filename as "NEWS.txt" and "abc.txt" but i am always
getting the output as "Not Found"


Can anyone please tell me where am i doing wrong????
It seems pretty apparent that lexists() nevert returns a true result.

Why not just

if os.path.exists(filename):
print os.path.realpath(filename)
else:
print "Not found"
also any suggestions to retrieve the filepath from a given filename is
highly appreciated.
Well, realpath returns the path of the file targeted after any symbolic
links have been evaluated, which may or may not be what you want. Have
you looked at os.path.abspath?

regards
Steve
 
M

music24by7

It seems pretty apparent that lexists() nevert returns a true result.

Why not just

if os.path.exists(filename):
    print os.path.realpath(filename)
else:
    print "Not found"


Well, realpath returns the path of the file targeted after any symbolic
links have been evaluated, which may or may not be what you want. Have
you looked at os.path.abspath?

regards
 Steve



Hi Steve,

I have tried your suggested code and also replaced os.path.realpath
with os.path.abspath but still getting the same result.
I want to know is there any workaround for retrieving the filepaths
given only filename

Regards,
Sudhir
 
S

Steve Holden

Hi Steve,

I have tried your suggested code and also replaced os.path.realpath
with os.path.abspath but still getting the same result.
I want to know is there any workaround for retrieving the filepaths
given only filename
What, you are saying that

os.path.exists(filename)

is returning false when the file exists? I find that hard to believe.

Please display some evidence so I can understand this.

regards
Steve
 
P

Peter Otten

Steve said:
What, you are saying that

os.path.exists(filename)

is returning false when the file exists? I find that hard to believe.

Please display some evidence so I can understand this.

Maybe it's about access rights?

$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$

I Don't know how this is handled on Windows...

Peter
 
E

Emile van Sebille

Peter said:
Maybe it's about access rights?

$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$

I Don't know how this is handled on Windows...

Here's one way....

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta # cygwin at work here...

C:\>python -c"import os; print os.path.exists('alpha/beta')"
True

C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha

C:\>python -c"import os; print os.path.exists('alpha/beta')"
False
 
M

music24by7

Peter said:
Maybe it's about access rights?
$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$
I Don't know how this is handled on Windows...

Here's one way....

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta  # cygwin at work here...

C:\>python -c"import os; print os.path.exists('alpha/beta')"
True

C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha

C:\>python -c"import os; print os.path.exists('alpha/beta')"
False

Hi,

This is the following code which i have used to retrieve the pathname
of a filename given by the user

filename = self.enText.get() # get the text entered in the
text box
if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
print os.path.abspath(filename)
else:
print "Not found"

actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.

But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.


Regards,
Sudhir
 
S

Steve Holden

Peter said:
Maybe it's about access rights?
$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$
I Don't know how this is handled on Windows...
Here's one way....

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta # cygwin at work here...

C:\>python -c"import os; print os.path.exists('alpha/beta')"
True

C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha

C:\>python -c"import os; print os.path.exists('alpha/beta')"
False

Hi,

This is the following code which i have used to retrieve the pathname
of a filename given by the user

filename = self.enText.get() # get the text entered in the
text box
if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
print os.path.abspath(filename)
else:
print "Not found"

actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.

But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.
Look, we aren't psychic. We can't debug code and directories we can't
see. Work with us here - give us the information we need to help you.

The actual code. A directory listing? Any error messages?

regards
Steve
 
M

music24by7

Peter Otten wrote:
Maybe it's about access rights?
$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$
I Don't know how this is handled on Windows...
Here's one way....
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta  # cygwin at work here...
C:\>python -c"import os; print os.path.exists('alpha/beta')"
True
C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha
C:\>python -c"import os; print os.path.exists('alpha/beta')"
False

This is the following code which i have used to retrieve the pathname
of a filename given by the user
        filename = self.enText.get() # get the text entered in the
text box
        if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
            print os.path.abspath(filename)
        else:
            print "Not found"
actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.
But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.

Look, we aren't psychic. We can't debug code and directories we can't
see. Work with us here - give us the information we need to help you.

The actual code. A directory listing? Any error messages?

regards
 Steve





Hi Steve,

Following is the code which i have written to display a GUI textbox
and get any name entered by the user and search the path of this
filename and then list it into an CSV file.

For this i initially created an textbox widget and added an button to
it.
Now, i have entered a filename (like NEWS.txt) in the text boz,
as you can see when i press the button i retrieve the text and then
search its filepath.
currently i am printing this filepath on the shell.


from Tkinter import *
import os
from os.path import realpath, exists, abspath
import tkMessageBox
import Tkinter
#import filePath

class GUIFrameWork(Frame):
"""This is the GUI"""

def __init__(self,master=None):
"""Initialize yourself"""

"""Initialise the base class"""
Frame.__init__(self,master)

"""Set the Window Title"""
self.master.title("Enter Text to search")

"""Display the main window"
with a little bit of padding"""
self.grid(padx=10,pady=10)
self.CreateWidgets()

def CreateWidgets(self):

self.enText = Entry(self)
self.enText.grid(row=0, column=1, columnspan=3)



"""Create the Button, set the text and the
command that will be called when the button is clicked"""
self.btnDisplay = Button(self, text="Display!",
command=self.Display)
self.btnDisplay.grid(row=0, column=4)

def Display(self):
"""Called when btnDisplay is clicked, displays the contents of
self.enText"""
filename = self.enText.get()
if os.path.exists(os.path.abspath(filename)):
print os.path.abspath(filename)
else:
print "Not found"
#tkMessageBox.showinfo("Text", "You typed: %s" %
os.path.abspath(os.path.dirname(filename)))

#filepath.mydir(self.enText.get())


if __name__ == "__main__":
guiFrame = GUIFrameWork()
guiFrame.mainloop()





User Input: NEWS.txt
Output: Not Found (though this file is actually present)




Regards,
Sudhir
 
J

John Machin

Peter Otten wrote:
Maybe it's about access rights?
$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$
I Don't know how this is handled on Windows...
Here's one way....
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta  # cygwin at work here...
C:\>python -c"import os; print os.path.exists('alpha/beta')"
True
C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha
C:\>python -c"import os; print os.path.exists('alpha/beta')"
False
Hi,
This is the following code which i have used to retrieve the pathname
of a filename given by the user
        filename = self.enText.get() # get the text entered in the
text box
        if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
            print os.path.abspath(filename)
        else:
            print "Not found"
actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.
But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.
Look, we aren't psychic. We can't debug code and directories we can't
see. Work with us here - give us the information we need to help you.
The actual code. A directory listing? Any error messages?
regards
 Steve

Hi Steve,

Following is the code which i have written to display a GUI textbox
and get any name entered by the user and search the path of this
filename and then list it into an CSV file.

For this i initially created an textbox widget and added an button to
it.
Now, i have entered a filename (like NEWS.txt) in the text boz,
as you can see when i press the button i retrieve the text and then
search its filepath.
currently i am printing this filepath on the shell.

from Tkinter import *
import os
from os.path import realpath, exists, abspath
import tkMessageBox
import Tkinter
#import filePath

class GUIFrameWork(Frame):
    """This is the GUI"""

    def __init__(self,master=None):
        """Initialize yourself"""

        """Initialise the base class"""
        Frame.__init__(self,master)

        """Set the Window Title"""
        self.master.title("Enter Text to search")

        """Display the main window"
        with a little bit of padding"""
        self.grid(padx=10,pady=10)
        self.CreateWidgets()

    def CreateWidgets(self):

        self.enText = Entry(self)
        self.enText.grid(row=0, column=1, columnspan=3)

        """Create the Button, set the text and the
        command that will be called when the button is clicked"""
        self.btnDisplay = Button(self, text="Display!",
command=self.Display)
        self.btnDisplay.grid(row=0, column=4)

    def Display(self):
        """Called when btnDisplay is clicked, displays the contents of
self.enText"""
        filename = self.enText.get()

Add some more code in here:
print "filename", repr(filename)
cwd = os.getcwd()
print "cwd", cwd
abspath = os.path.abspath(filename)
print "abspath", repr(abspath)
exists = os.path.exists(abspath)
print "exists", exists
and copy/paste the output into your reply.
Also tell us the name of the folder that the file allegedly exists in,
with a folder listing to prove it.
Also show us the result of using the ATTRIB command on your file, like
in the following examples:

C:\junk>attrib c:\io.sys
SHR C:\IO.SYS

C:\junk>attrib c:\python26\python.exe
A C:\python26\python.exe

Again, use copy/paste in your reply.
 
M

music24by7

Hi Dennis Thanks for your reply and also the detailed explanation.
Or do you mean you want something that, given a bare name, searches
your file system to find where a file with that name actually is?

Yes, this is what i exactly needed.
I have found something interesting to do this using the os.walk(path)
function, and it worked....
I am pasting the code which i used for this:



testpath=r"C:\\"
logpath=r"C:\Pathfinder.txt"
csvpath=r"C:\Pathfinder.csv"
import os, csv

def logData(d={}, logfile="c://filename999.txt", separator="\n"):
"""Takes a dictionary of values and writes them to the provided
file path"""
logstring=separator.join([str(key)+": "+d[key] for key in
d.keys()])+"\n"
f=open(logfile,'a')
f.write(logstring)
f.close()
return
def walker(topPath,csvpath):
fDict={}
logDict={}
limit=1000
freed_space=0
items=0
fileHandle = csv.writer(open(csvpath, 'w'))
fileHandle.writerow(['Index','Path'])
for root, dirs, files in os.walk(topPath):
for name in files:
fpath=os.path.join(root,name)
logDict["Name"]=name
logDict["Path"]=fpath
if name.find("NEWS"):
continue
else:
logData(logDict, logpath, "\t")
fDict[items] = name
items=len(fDict.keys())
fileHandle.writerow([items,fpath])
print "Dict entry: ",items,
print "Path: ",fpath
if items > limit:
break
if items > limit:
break
walker(testpath,csvpath)



Finally thank you all very much for the patience to listen to me.


Regards,
Sudhir
 
S

Steve Holden

Peter Otten wrote:
Maybe it's about access rights?
$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$
I Don't know how this is handled on Windows...
Here's one way....
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta # cygwin at work here...
C:\>python -c"import os; print os.path.exists('alpha/beta')"
True
C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha
C:\>python -c"import os; print os.path.exists('alpha/beta')"
False
Hi,
This is the following code which i have used to retrieve the pathname
of a filename given by the user
filename = self.enText.get() # get the text entered in the
text box
if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
print os.path.abspath(filename)
else:
print "Not found"
actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.
But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.
Look, we aren't psychic. We can't debug code and directories we can't
see. Work with us here - give us the information we need to help you.

The actual code. A directory listing? Any error messages?

regards
Steve





Hi Steve,

Following is the code which i have written to display a GUI textbox
and get any name entered by the user and search the path of this
filename and then list it into an CSV file.

For this i initially created an textbox widget and added an button to
it.
Now, i have entered a filename (like NEWS.txt) in the text boz,
as you can see when i press the button i retrieve the text and then
search its filepath.
currently i am printing this filepath on the shell.


from Tkinter import *

So this is Python 2.x ...
import os
from os.path import realpath, exists, abspath
import tkMessageBox
import Tkinter

Not sure why you bother to import Tkinter when you have above just
imported everything *from* Tkinter ...
#import filePath

class GUIFrameWork(Frame):
"""This is the GUI"""

def __init__(self,master=None):
"""Initialize yourself"""

"""Initialise the base class"""
Frame.__init__(self,master)

"""Set the Window Title"""
self.master.title("Enter Text to search")

"""Display the main window"
with a little bit of padding"""
self.grid(padx=10,pady=10)
self.CreateWidgets()

def CreateWidgets(self):

self.enText = Entry(self)
self.enText.grid(row=0, column=1, columnspan=3)



"""Create the Button, set the text and the
command that will be called when the button is clicked"""
self.btnDisplay = Button(self, text="Display!",
command=self.Display)
self.btnDisplay.grid(row=0, column=4)

def Display(self):
"""Called when btnDisplay is clicked, displays the contents of
self.enText"""
filename = self.enText.get()
if os.path.exists(os.path.abspath(filename)):
print os.path.abspath(filename)

First, move this line up one (losing an indent level) so you always
print the full path. This will verify you are looking where you think
you are looking.
else:
print "Not found"
#tkMessageBox.showinfo("Text", "You typed: %s" %
os.path.abspath(os.path.dirname(filename)))

#filepath.mydir(self.enText.get())


if __name__ == "__main__":
guiFrame = GUIFrameWork()
guiFrame.mainloop()


User Input: NEWS.txt
Output: Not Found (though this file is actually present)
Thanks for the information. I'm wondering whether there might be some
filename encoding issue here, but others may have some better ideas.

regards
Steve
 
S

Steve Holden

Dennis said:
WARNING -- I will probably NOT see your response; since 90+% of the
spam in comp.lang.python is injected via googlegroups and gmail
accounts, my client is configured to filter out messages with a from
address having gmail.com. I only found this message by doing fetches on
the reference header of the replies that did get by the filter.
Well, since it's more likely you'll see this, let me tell you that if
you access the group via gmane (as I do) you rarely see the spam anyway.
There's been a lot more work on spam filtering lately.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top