【问题标题】:the .write function adds a new line after the sentinel value has been reached.write 函数在达到标记值后添加一个新行
【发布时间】:2021-02-21 07:11:54
【问题描述】:
infile = open("inputex1.txt","r")
line = infile.readline()
print("1 "+line, end="")
i = 2
while line !="" :
     line = infile.readline()
     print(str(i)+" "+line, end="")
     i+=1
infile.close()

文本文件是:

Mary had a little lamb,
whose fleece was white as snow.
And everyWhere that Mary went,
The Lamb was sure to go

然而输出是:

1 Mary had a little lamb,
2 whose fleece was white as snow.
3 And everyWhere that Mary went,
4 The Lamb was sur to go
5 

我的问题是,为什么它到达第五行后一直进入while循环?为什么最后是5?

【问题讨论】:

  • 因为你在最后一行之后又读了一行,这将导致一个空字符串。或者换一种说法,因为您在打印之后检查该行是否为空。
  • 这能回答你的问题吗? How should I read a file line-by-line in Python?
  • mkrieger 确定了您的代码的问题,但请注意,您不应该使用这种方法来逐行迭代文件,文件对象是行上的迭代器 你可以直接遍历它们:for line in infile: ... 基本上,readlinereadlines 是 Python 非常旧版本的遗物。在专业环境中编写 Python 的四年中,我使用它们的次数恰好为零。您可以分别使用next(infile)list(infile)。通常,您只需直接遍历文件对象以进行一些逐行处理

标签: python


【解决方案1】:

infile.readline() 将在完整读取文件时回答一个空字符串。

所以当你执行print(str(i) + " " + line, end="") 时,它会打印出5

你应该这样做:

i = 2
while line !="" :
     line = infile.readline()
     if line:
         print(str(i)+" "+line, end="")
         i+=1

但你也可以这样简化:

for i, line in enumerate(infile, 1):
    print(str(i) + " " + line, end="")

或者如果你有 python 3.6+:

for i, line in enumerate(infile, 1):
    print(f"{i} {line}", end="")

另请参阅Wasif Hasan’s answer,了解with 的用法。

【讨论】:

    【解决方案2】:

    在读取文件时,它们可以有前导/尾随换行符,因此您可以像这样以最佳方式使用with

    i = 1
    with open("inputex1.txt","r") as f:
      for line in f:
          print(i,line)
          i += 1
    

    我使用它读取了一个python文件,输出:

    1 entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
    
    2            {'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
    
    3            {'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434'},
    
    4            {'First Name': 'Talha', 'Last Name': 'Jones', 'Age': '22', 'Telephone': '3343434'}]    
    
    5 search = input("type your search: ")
    
    6 found = False
    
    7 print(search)
    
    8 for person in entries:
    
    9   if person["Last Name"] == search:
    
    10     found = True
    
    11     print("Here are the records found for your search")
    
    12     for e in person:
    
    13       print(e, ":", person[e])
    
    14 
    
    15 if not found:
    
    16   print("There is no record found as you search Keyword")
    

    【讨论】:

    • 是的,with 非常重要,因为如果出现问题,您的文件描述符 f 无论如何都会关闭。
    猜你喜欢
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多