Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python .write函数在达到sentinel值后添加新行_Python - Fatal编程技术网

Python .write函数在达到sentinel值后添加新行

Python .write函数在达到sentinel值后添加新行,python,Python,文本文件为: infile = open("inputex1.txt","r") line = infile.readline() print("1 "+line, end="") i = 2 while line !="" : line = infile.readline() print(str(i)+" "+line, end="")

文本文件为:

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
我的问题是,为什么它在到达第五行后继续进入while循环?为什么最后有一个5?

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

因此,当您执行
打印时(str(i)+“”+line,end=“”)
,它将打印
5

你应该这样做:

i=2
一边排队="" :
line=infle.readline()
如果行:
打印(str(i)+“”+行,end=“”)
i+=1
但你也可以这样简化它:

对于i,枚举中的行(infle,1):
打印(str(i)+“”+行,end=“”)
或者,如果您有python 3.6+:

对于i,枚举中的行(infle,1):
打印(f“{i}{line}”,end=”“)

另请参阅有关
with
用法的信息。

从文件中读取时,它们可以有前导/尾随换行符,因此您可以以如下最佳方式使用
with

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 
我使用它读取了一个python文件,输出:

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

因为您在最后一行之后又读了一行,这将导致一个空字符串。或者换一种说法,因为打印后检查行是否为空。这是否回答了您的问题?mkrieger指出了代码的问题,但请注意,您不应该使用这种方法逐行迭代文件,文件对象是可以直接迭代的行上的迭代器:
对于infle中的行:…
基本上,
readline
readline
都是Python非常旧版本的遗物。在专业环境下编程Python的四年中,我几乎没有使用过它们。您可以分别使用
next(infle)
list(infle)
。通常,您只需直接在file对象上循环以进行逐行处理是的,的
非常重要,因为如果出现问题,您的文件描述符
f
无论发生什么情况都将关闭。
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")