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
f.close()
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?
Thanks
2 Answers 2
from os.path import abspath
full_path = abspath(filename)
Comments
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
4 Comments
open(fname) it will look for the file in the directory where you're running your script - not the directory you typed into the prompt. That is, instead of trying to open /home/diego/test/test it tries to open /home/diego/Documents/progra/python/antivirus/test because you only told it to open "test"os.path.join(directory, fname) and you'll get "/home/diego/test/test"
fname, likeopen(os.path.join(directory, fname))os.path.abspath("mydir/myfile.txt")os.path.abspath(fname)won't help here because using the current code, Python can't find the file becausefnameis not a valid relative path.