Diego Velez Diego Velez - 2 years ago 267
Python Question

Get absolute path of file in python

I was searching how to get the absolute path of a file on python but haven't had much luck. here is my code

import os

directory = raw_input("What's the directory? ")
print "Reading files.."
listing = os.listdir(directory)
for fname in listing:
with open(fname) as f:
if "yes" in f.read():
print f.name

my problem is this... the listing is perfectly fine.. but when the listdir method passes the variable to the open method, the variable is passes without the absolute path, so it won't read the files because it is reading a file that has no path.. here is a sample of the error

What's the directory? /home/diego/test
Reading files..
Traceback (most recent call last):
File "/home/diego/Documents/progra/python/antivirus/antivirus.py", line 14, in
with open(fname) as f:
IOError: [Errno 2] No such file or directory: 'test'

Can anyone help me with it?


Answer Source

Ok, so your problem hasn't got anything to do with absolute paths. The problem is that you're trying to open a file that exists in another directory using only it's filename. Use os.path.join to create the complete file name and use that:

for fname in listing:
    full_name = os.path.join(directory, fname)
    with open(full_name) as f:
        if "yes" in f.read():
            print f.name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download