Skip to content Skip to sidebar Skip to footer

Program Can't Read Path Name From Arg. "no Such File Or Directory"

I have a new problem with a python script. When I try to run it passing a path as argument to the program it returns the error message: 'No such file or directory'. The program is

Solution 1:

A problem related to your path is this:

path = sys.argv[0]

argv[0] refers to the command run (usually the name of your Python script) .. if you want the first command line argument, use index 1, not 0. I.e.,

path = sys.argv[1]

Example script tmp.py:

import sys, os
print sys.argv[0]
print sys.argv[1]

and: python tmp.py d:\users gives:

 tmp.py
 d:\users

Also two syntax errors:

ifos.path.exist(path):  # the functionisexists()-- note the s at the end
        abspath = os.path.abspath(path):  # there should be no : here

Solution 2:

os.listdir returns a list of the names of files in the directory, but not their path. E.g. you have a directory 'test' and files a,b and c in it:

os.listdir("test") #-> returns["a", "b", "c"]

if you want to open the files, you need to use the full path:

from os import path, listdir
def getpaths(dirname):
    return [path.join(dirname, fname) for fname in listdir(dirname)]
getpaths("test") #-> returns ["test/a", "test/b", "test/c"]

the full solution to your problem in five lines:

import sys, os
dir = sys.argv[1]
files = [open(os.path.join(dir, f)) for f in os.listdir(dir)]
first2lines = ['\n'.join(f.read().split("\n")[:2]) for f in files]
print'\n'.join(first2lines)

Post a Comment for "Program Can't Read Path Name From Arg. "no Such File Or Directory""