在Python中逐行读取文本文件
我创建了一个这样的文本文件:
fo = open("foo.txt", "wb")
fo.write("begin \n")
fo.write("end \n")
fo.write("if \n")
fo.write("then \n")
fo.write("else \n")
fo.write("identifier \n")
input = raw_input("Enter the expression : ")
print input
fo = open("foo.txt" , "rt")
str = fo.read(10)
print "Read string is : ", str
fo.close()
我应该怎么做才能逐行读取这个文本文件呢?我试过使用fo.read()和fo.readlines(),但是没有得到我想要的结果!!!
3 个回答
0
首先,你打开文件的方式不对(你用的是二进制模式,而不是文本模式,下面的打开参数可以看到)。你需要使用readlines方法来逐行读取文件的内容。
#Using a context manager to open the file in write text mode
with open("foo.txt", "w") as fo:
fo.write("begin \n")
#write other lines...
...
input = raw_input("Enter the expression : ")
print input
#Open in read text mode
with open("foo.txt" , "r") as fi:
for line in fi.readlines():
print "Read string is : ", str
0
你正在打开一个文件来写东西,但在尝试读取之前没有把它关闭。你需要在fo.read
之前加上fo.close()
。
另外,read(10)
是从文件中读取10个字节的数据,而wb
表示你是在写二进制数据。我不太确定这是不是你想要的……
1
它是可以工作的,但你没有正确使用它:
for line in fo.readlines():
print line