Unable to properly read the lines from a file

给你一囗甜甜゛ 提交于 2020-07-22 06:12:10

问题


I have file, which i wrote using a python script. The file is large and contain more than a 1000 lines, and each line is very large and it goes like :(shortened)

1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
  1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
  1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
2 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
  1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
  1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
3 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
  1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
...

And see, each line could take the space of 3 lines while displaying it in the monitor.
When I try :

fp = open('data.txt','r')
c = 0
for line in fp:
    c += 1
print("No. of line = ",c)

I get the correct value, and when I use the read() function, I get a different value, as in:

fp = open('data.txt','r')
c = 0
data = fp.read()
for line in data:
    c += 1
print("No. of line = ",c)

Can somebody explain, what is the difference between using the read() function, and not using it ?

Thanks in advance...


回答1:


Using

data = fp.read()
for line in data:
    c += 1 

you read all in one string and for-loop treats this string as list of chars - so you count chars.

You have to use readlines() to get list of lines and count lines in this list

data = fp.readlines()
for line in data:
    c += 1 

BTW: The same result to count chars

data = fp.read()
c = len(data) 

and to count lines

data = fp.readlines()
c = len(data)

BTW: You could also use print() to see what you have in variable

data = fp.read()
print(data[0])
print(data[:3])
print(data)

and

data = fp.readlines()
print(data[0])
print(data[:3])
print(data)

If you want to test in the one script then you have to close and open fail again or use fp.seek(0) to move to beginning of file before you read again.


To works with lines you should use

fp = open('data.txt','r')

for line in fp:
    # ...code ...

fp.close()

or

fp = open('data.txt','r')
all_lines = fp.readlines()

for line in all_lines:
    # ...code ...

fp.close()

The same with with ... as ...

with open('data.txt','r') as fp:
    for line in fp:
        # ...code ...

or

with open('data.txt','r') as fp:
    all_lines = fp.readlines()
    for line in all_lines:
        # ...code ...


来源:https://stackoverflow.com/questions/62193494/unable-to-properly-read-the-lines-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!