[英]Read a text file in python line wise
我创建了以下文本文件:
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(),但没有得到预期的输出!!!
它正在工作,但您没有以正确的方式使用它:
for line in fo.readlines():
print line
您正在打开文件进行写入,但是在尝试读取文件之前没有关闭它。 您需要添加一个fo.close()
的前fo.read
同样, read(10)
从文件中读取10个字节的数据,而wb
表示您正在写入二进制数据。 我不太确定这就是你想要的...
对于初学者,您将以错误的模式打开文件(二进制,而不是文本,请注意下面的打开参数)。 您需要使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.