【问题标题】:Unable to properly read the lines from a file无法正确读取文件中的行
【发布时间】:2020-09-23 08:53:47
【问题描述】:

我有文件,我使用python script 编写的。该文件很大,包含超过 1000 行,并且每一行都非常大,就像 :(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
...

你看,每行在显示器上显示时可以占用 3 行的空间。
当我尝试时:

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

我得到了正确的值,当我使用read() 函数时,我得到了一个不同的值,如:

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

谁能解释一下,使用read()函数和不使用它有什么区别?

提前谢谢...

【问题讨论】:

  • 您必须使用readlines() 而不是read()。第二个代码全部读取为一个字符串,您 for 循环从此字符串中获取字符并计算字符数。第一个按行读取的代码并计算行数。
  • 顺便说一句:在第一个c = len(fp),在第二个c = len(data)

标签: python arrays python-3.x file file-io


【解决方案1】:

使用

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

您在一个字符串中读取所有内容,for-loop 将此字符串视为字符列表 - 所以您计算字符数。

您必须使用readlines() 来获取行列表并计算此列表中的行数

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

顺便说一句:计算字符的结果相同

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

计算行数

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

顺便说一句:您也可以使用print() 查看变量中的内容

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

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

如果您想在一个脚本中进行测试,那么您必须再次关闭并打开失败,或者在再次阅读之前使用fp.seek(0) 移动到文件的开头。


要使用线条,您应该使用

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

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

fp.close()

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

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

fp.close()

with ... as ...也一样

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

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

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2018-07-24
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多