我有一个python脚本的新问题.当我尝试运行它将路径作为参数传递给程序时,它返回错误消息:" No such file or directory".该程序应该遍历路径名指定的目录,以查找文本文件并打印出前两行.
是的确,这是家庭作业,但我看了很多关于os和sys的内容,但仍然没有得到它.你们有些退伍军人能帮助新手吗?谢谢
#!/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 …Run Code Online (Sandbox Code Playgroud)