0

I have this code that will let the user choose which file he wants to update by passing an argument in the command line, and then it do some more things but I have not included that here:

import sys
import os
from sys import argv

path = "/home/Desktop/python/test"
files = os.walk( path )
filename = argv[1]

if filename in files:
    inputFile = open(filename, 'r')
else:
    print "no match found"
    sys.exit()
    inputFile.close()

When I run the script it keeps giving me "no match found" but im pretty sure the file is there. I cant see what Im doing wrong

2
  • 1
    Use os.listdir instead of os.walk to get a list of files in path instead of a generator. Commented Dec 2, 2015 at 8:40
  • @Holt: but take into account you still need to use os.path.join(path, filename) to be able to open the file. Commented Dec 2, 2015 at 8:53

2 Answers 2

3

os.walk() returns a generator, one that produces tuples with (root, directories, files) values for each iteration.

You can't use that generator to test for a single file, not with a simple in membership test.

You'll also need to re-instate the whole path; you can't just open an unclassified filename without the directory it lives in. Just use a for loop here, and break once you found it. The else suite on a for loop only executes when you did not use break (e.g. the file was not found):

path = "/home/Desktop/python/test"
filename = argv[1]

for root, directories, files in os.walk(path):
    if filename in files:
        full_path = os.path.join(root, filename)
        break
else:
    print "no match found"
    sys.exit()

with open(full_path) as input_file:
    # do something with the file

I added a with statement to handle the lifetime of the file object; once the with block is exited the file is automatically closed for you.

Sign up to request clarification or add additional context in comments.

1 Comment

@Holt: thanks; was in a bit of a hurry, I knew I should have checked.
1

Alternatively, you may use following code snippet.

import os.path
filename = argv[1]
path = "/home/Desktop/python/test/"
if os.path.isfile(path + filename):
   inputFile = open(path + filename, "r")
else:
   print "File Not Found"

2 Comments

This will check for filename in the current directory, not in path.
You really should use os.path.join(); it'll take care of such details as adding a missing path separator at the end, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.