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 supposed to iterate through a directory specified by the path name to look for textfiles and print out the first two lines.
Yes indeed, it is homework, but I have looked and read alot about os and sys but still don’t get it. Can some of you veterans please help a newbie? Thanks
#!/usr/bin/python2.7
#print2lines.py
"""
program to find txt-files in directory and
print out the first two lines
"""
import sys, os
if (len(sys.argv)>1):
path = sys.argv[0]
if os.path.exist(path):
abspath = os.path.abspath(path):
dirlist = os.listdir(abspath)
for filename in dirlist:
if (filename.endswith(".txt")):
textfile = open(filename, 'r')
print filename + ": \n"
print textfile.readline(), "\n"
print textfile.readline() + "\n"
else:
print "passed argument is not valid pathname"
else:
print "You must pass path to directory as argument"
os.listdirreturns 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:if you want to open the files, you need to use the full path:
the full solution to your problem in five lines: