5

我正在为类编写一个程序,该程序打开一个文件,计算字数,返回字数,然后关闭。我了解如何做所有事情,除了让文件打开并显示文本这就是我到目前为止所拥有的:

    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

4 回答 4

15

You're using open() twice, so you've actually already opened the file, and then you attempt to open the already opened file object... change your code to:

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

The TypeError is saying that it cannot open type _io.TextIOWrapper which is what open() returns when opening a file.


Edit: You should really be handling files like so:

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

because when the with statement block is finished, it will handle file closing for you, which is very nice. The r before the string will prevent python from interpreting it, leaving it exactly how you formed it.

于 2012-10-27T08:22:21.847 回答
0

第一行的问题。应该是一个没有open的简单赋值。即fname = "c:\Python32\getty.txt。另外,你最好避开反斜杠(例如'\')或为字符串文字加上一个'r'(这不是你的问题具体的程序,如果你的文件名中有特殊字符,购买可能会成为问题)。总的来说,程序应该是:

fname = r"c:\Python32\getty.txt"
file = open(fname,'r')
data = file.read()
print (data)
于 2012-10-27T08:30:07.373 回答
0

将名称部分放在文件之后,例如:

data = file.name.read()
于 2017-05-18T11:11:25.440 回答
-1

您会收到此类错误,因为当您编写文件目录时,您使用的是反斜杠\,这并不好。您应该使用正斜杠/。例如

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

从现在开始,您将获得所有文件代码read

文件模式(“r”、“U”、“w”、“a”,可能添加了“b”或“+”)

编辑:

如果您不想更改斜杠,则只需r在字符串前添加一个:r"path"

fname = r"C:\Python32\getty.txt"
file_ = open(fname, 'r')
data = file_.read()
print data
于 2012-10-27T14:03:58.773 回答