This code not working, need suggetions
Chris Rebert
clp2 at rebertia.com
Mon Apr 23 03:48:02 EDT 2012
On Sun, Apr 22, 2012 at 11:16 PM, Anirudh Srinivasan <anirudh at nutanix.com>
wrote:
>
> My code lists the files and directory under a folder and if we want to
> read the file it uses the function cat.
>
> But the function cat(get_file) is not working , any suggetions?
Please specifically state exactly how it's deviating from the desired
behavior (including the full text of any error messages and/or
exception tracebacks, though I don't think those will apply here).
I note that you don't actually call cat() anywhere in your program.
> Here is my code:
>
>
> #!/usr/bin/python
>
> import os
> import sys
> import commands
> #import cat
Such an import (if uncommented) would require you had a *module* named `cat`.
> def listdir(s):
I would suggest renaming this function to avoid confusion with os.listdir().
> try:
> file = os.listdir(s)
Don't use `file` as a variable name. It shadows the name of the
built-in `file` type.
Also, `file` isn't a sensible variable name in this context; it's a
list (as opposed to a single item) and may also contain directory
names. And it contains strings rather than file objects.
> for files in file:
> path = os.path.join(s, files)
> print path
> #cmd = 'ls -l '+ path
> #g= commands.getstatusoutput(cmd)
The `commands` module has been deprecated. Its successor is `subprocess`:
http://docs.python.org/library/subprocess.html
> #print g[1]
> except OSError:
> print "No such file or directory"
>
>
> def main():
> listdir(sys.argv[1])
>
>
> if __name__ == "__main__":
> main()
`if __name__ == "__main__":` should normally come at the end of the
script, after all `def`s.
>
> def cat(get_file):
> f = open(get_file, "rU")
> text = f.read()
> print text,
You should `.close()` the file once you're done with it. Or use the
`with` statement (http://www.python.org/dev/peps/pep-0343/ ).
> get_file = raw_input("Which file would you like to browse ?")
Presumably this line should be under your `if __name__ ==
"__main__":`? And you're not actually doing anything with `get_file`
after you obtain it from the user...
Regards,
Chris
More information about the Python-list
mailing list