找不到文件在python中读取文本时出错

时间:2013-10-09 03:48:05

标签: python

我正在尝试使用以下脚本通过python读取硬盘上的文本文件:

fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

但它出现以下错误:

IOError                                   Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'

我也尝试过其他方式:

with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
    print f.read()

结束了同样的错误。文本文件存在于指定的目录中。

2 个答案:

答案 0 :(得分:5)

替换

fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

在这里,我创建了一个原始字符串(r"")。这将导致"\t"之类的内容不被解释为制表符。

没有原始字符串的另一种方法是

fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")

这会逃避反斜杠(即"\\" => \)。


更好的解决方案是使用os模块:

import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')

这会以独立于操作系统的方式创建您的路径,因此您不必担心这些事情。


最后一个注意事项......总的来说,我认为你应该使用你在问题中提到的with构造......为了简洁,我没有回答。

答案 1 :(得分:0)

我遇到了同样的问题。由于不同的文件路径符号Python而导致此问题。
例如,Windows中的文件路径读取时带有反斜杠,例如:“ D:\ Python \ Project \ file.txt”

但是Python读取带有正斜杠的文件路径,例如:“ D:/Python/Project/file.txt”

我毫不费力地使用了r“ filepath.txt”,“ os.path.join”和“ os.path.abspath”。 os库还以Windows表示法生成文件路径。然后我只求助于IDE表示法。

如果“ file.txt”位于同一目录中,则不会遇到此错误,因为文件名已附加到工作目录中。

PS:我在Windows计算机上将Python 3.6与Spyder IDE结合使用。

相关问题