leaker
leaker

Reputation: 15

command line arguments using python

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

Upvotes: 0

Views: 127

Answers (2)

niyasc
niyasc

Reputation: 4490

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"

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121306

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.

Upvotes: 3

Related Questions