简体   繁体   中英

Read a text file in python line wise

I have created the following text file :

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()

What should i be doing to read the text file line-wise?? I tried fo.read() and fo.readlines() but i am not getting the expected output!!!

It's working but you didn't use it in the right way:

for line in fo.readlines():
    print line

You are opening the file for writing, but not closing it before trying to read from it. You need to add a fo.close() before the fo.read

also, read(10) reads 10 bytes of data from the file, and wb means your'e writing binary data. I'm not so sure thats what you want...

For starters, you're opening the file in the wrong mode (binary, instead of text, notice the open arguments below). You need to use the readlines method to iterate over the lines of the file.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM