从提到的目录中读取文件时出错(Python 3.2)

时间:2013-09-26 15:33:29

标签: python

对于下面发布的代码

我在文件夹C中保留了一个名为nd1.txt的记事本文档:\ TempFiles

import os,file,storage
database = file.dictionary()
tools = storage.misc()
lui = -1

def sendWord(wrd, findex):
    global lui
    if findex!=lui:
        tools.refreshRecentList()
        lui = findex
    if tools.mustIgnore(wrd)==0 and tools.toRecentList(wrd)==1:
        database.addWord(wrd,findex)        
def showPostingsList():
    database.display()

def parseFile(nfile, findex):
    for line in nfile:
        pl = line.split()
        for word in pl:
            print(word)
            sendWord(word.lower(),findex)

def parseDirectory():
    files = [open(f) for f in os.listdir('C:\TempFiles')]
    findex = 0
    for nf in files:
        parseFile(nf,findex)
        findex+=1

def main():
    parseDirectory()
    showPostingsList()

main()

现在每当我执行代码时,我都会收到以下错误信息

Traceback (most recent call last):
  File "E:\Documents\Information Retrieval\postingsList.py", line 39, in <module>
main()
  File "E:\Documents\Information Retrieval\postingsList.py", line 36, in main
parseDirectory(dirname)
  File "E:\Documents\Information Retrieval\postingsList.py", line 28, in parseDirectory
files = [open(f) for f in os.listdir('C:\TempFiles')]
  File "E:\Documents\Information Retrieval\postingsList.py", line 28, in <listcomp>
files = [open(f) for f in os.listdir('C:\TempFiles')]
FileNotFoundError: [Errno 2] No such file or directory: 'nd1.txt'

即使文件在上述文件夹中存在,加上每个功能都正常工作,我还是用虚拟数据检查了

任何人都可以告诉我我的代码出错了吗?

3 个答案:

答案 0 :(得分:1)

os.listdir为您提供文件的名称,而不是完整路径。您需要在调用open之前添加路径,最好使用os.path.join

答案 1 :(得分:0)

正如伏都林所述,os.listdir仅提供names of files

您需要查看os.path.abspath module

此外,值得使用一些日志代码来解决问题 -

import os,file,storage
import logging

logging.basicConfig(level=logging.DEBUG)
database = file.dictionary()
tools = storage.misc()
lui = -1

def sendWord(wrd, findex):
    global lui
    if findex!=lui:
        tools.refreshRecentList()
        lui = findex
    if tools.mustIgnore(wrd)==0 and tools.toRecentList(wrd)==1:
        database.addWord(wrd,findex)        
def showPostingsList():
    database.display()

def parseFile(nfile, findex):
    for line in nfile:
        pl = line.split()
        for word in pl:
            print(word)
            sendWord(word.lower(),findex)

def parseDirectory():
    files = [open(f) for f in os.listdir('C:\TempFiles')]
    findex = 0
    logging.debug(os.path.abspath(os.curdir))
    for nf in files:
        logging.debug(os.path.exists(nf))
        parseFile(nf,findex)
        findex+=1

def main():
    parseDirectory()
    showPostingsList()

main()

答案 2 :(得分:0)

因为os.listdir将返回文件名而不是文件路径。您最好在文件名

之前添加C:\TempFiles\