为什么我的程序没有读取引用文件(fileName)中的第一行代码


def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline()
count=0
while text != "":
text=str(count)     
count+=1
text=infile.readline()

print(str(count)+ ": " + text)
infile.close()     
main()

-引用的.txt文件只有两个元素

44

33

-该代码的输出应该看起来像

1:44

2:33

-我的输出是

1:33

2:

我不知道为什么程序没有在引用的.txt文件中拾取第一行。行号是正确的,但是33应该是44的第二位。

评论中解释了原因:

def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline()  ##Reading the first line here but not printing
count=0
while text != "":
text=str(count)     
count+=1
text=infile.readline() ##Reading the 2nd line here
print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first 
##line
infile.close()     

main()

将程序修改为:

def main():
read()
def read():
fileName= input("Enter the file you want to count: ")
infile = open(fileName , "r")
text = infile.readline()
count = 1                             # Set count to 1
while text != "":
print(str(count)+ ": " + str(text))   # Print 1st line here
count = count + 1                     # Increment count to 2 
text = infile.readline()              # Read 2nd line 
infile.close()                           # Close the file

main()
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
with open(fileName,'r') as f:
print('n'.join([' : '.join([str(i+1),v.rstrip()]) for i,v in enumerate(f.readlines())]))
main()

我对您的read函数感到非常困惑。您首先将第一行读入文本:

text=infile.readline()

在这一点上,文本可能包含44

然后,在你对它做任何事情之前,你立即用覆盖它,从而摧毁这个值

text = str(count)

你在印刷任何东西之前先读了两行字。

您应该先打印text的值,然后再用下一个readline覆盖它。

只需将print语句移动到readline:之前

while text != "":
count+=1
print(str(count)+ ": " + text)
text=infile.readline()

最新更新