如何让python打开外部文件?

时间:2012-10-27 07:51:10

标签: python file-io typeerror

我正在编写一个程序,用于打开文件,计算单词,返回单词数,然后关闭。我知道如何做所有事情激发让文件打开并显示文本这是我到目前为止:

    fname = open("C:\Python32\getty.txt") 
    file = open(fname, 'r')
    data = file.read()
    print(data)

我得到的错误是:

    TypeError: invalid file: <_io.TextIOWrapper name='C:\\Python32\\getty.txt' mode='r'
    encoding='cp1252'>

文件保存在正确的位置,我检查了拼写等。我正在使用pycharm来处理这个问题,而我试图打开的文件是在记事本中。

4 个答案:

答案 0 :(得分:14)

您正在使用open()两次,因此您实际上已经打开了该文件,然后您尝试打开已打开的文件对象...将您的代码更改为:

fname = "C:\\Python32\\getty.txt"
infile = open(fname, 'r')
data = infile.read()
print(data)

TypeError表示无法打开_io.TextIOWrapper类型,这是open()在打开文件时返回的内容。


编辑:您应该真正处理这样的文件:

with open(r"C:\Python32\getty.txt", 'r') as infile:
    data = infile.read()
    print(data)

因为当with语句块完成时,它会为你处理文件关闭,这非常好。 字符串前面的r将阻止python解释它,使其完全按照你的方式形成它。

答案 1 :(得分:0)

第一行有问题。应该是没有开放的简单任务。 ie fname =“c:\ Python32 \ getty.txt 。另外,你最好还是去反斜杠(例如'\')或者为字符串文字放一个'r'(这个对于您的特定程序不是问题,如果您的文件名中有特殊字符,则购买可能会成为问题。)总体而言,该程序应该是:

fname = r"c:\Python32\getty.txt"
file = open(fname,'r')
data = file.read()
print (data)

答案 2 :(得分:0)

将名称放在文件后面,如:

data = file.name.read()

答案 3 :(得分:-2)

您遇到此类错误,因为在您编写文件目录时,您使用的是反斜杠\,这样做并不好。您应该使用正斜杠/。 E.g

file_ = open("C:/Python32/getty.txt", "r")
read = file_.read()
file_.close()
print read

从现在开始,您获得了read下的所有文件代码。

文件模式('r','U','w','a',可能添加'b'或'+')

编辑:

如果您不想更改斜杠,只需在字符串前添加rr"path"

fname = r"C:\Python32\getty.txt"
file_ = open(fname, 'r')
data = file_.read()
print data