IOError:[Errno 2]没有这样的文件或目录Python

时间:2012-05-11 03:34:05

标签: python file file-io io

我有这段代码,试图找到*.vm个文件,并将它们发送到另一个

我做过的模块,它应该读取这些行。

这是主文件:

def VMTranslte(fileName):
print "FILEOVER ",fileName
from parser import Parser
from codeWriter import CodeWriter
if (fileName[-3:] == ".vm"):
    outputFile = fileName[:-3]+".asm"
    myWrite = CodeWriter(outputFile)
    myWrite.setFileName(fileName)
    myParser = Parser(fileName)
    myWrite.setFileName(fileName);
    translate(myParser,myWrite)
else:
    if fileName[-1:] == "/": <===== CHECKS FOR DIRECTORY
        mystr = fileName.split('/')[-2]
        mystr = mystr.split('.')[0]+".asm"
        outputFile = fileName+mystr
    else:
        outputFile = fileName+".asm"
    myWrite = CodeWriter(outputFile)
    for child in os.listdir(fileName):
        if child.endswith('.vm'): <===== CHECK IF THERE IS *.vm FILE
            print "CHILD: ",child <===== PRINTS THE FILE WANTED (MEANING FINDS IT)
            myWrite.setFileName(child);
            myParser = Parser(child) <===== CALLS THE READER MODULE DESCRIBED AT THE BOTTOM
            translate(myParser,myWrite) 
myWrite.close()

应该读取这些行的模块:

#Constructor for Parser module.
def __init__(self,fileName):
    import re
    self.cmds = []
    self.counter = 0
    myFile = open(fileName, 'r') <=====ERROR OVER HERE
    fLines = myFile.readlines()
    for value in fLines : 
        lineStrip = value.strip()
        if not (re.match("//",lineStrip) or len(lineStrip)==0):
            self.cmds.append(lineStrip)

错误是:

  File "/Users/***/Desktop/dProj7/parser.py", line 19, in __init__
  myFile = open(fileName, 'r')
  IOError: [Errno 2] No such file or directory: 'BasicTest.vm'

很明显,脚本找到了文件,(他进入第一个循环),

这里发生了什么?

1 个答案:

答案 0 :(得分:3)

os.listdir不包含路径,只包含文件名。您可能希望以os.path.join(fileName, child)为参数调用Parser。