我试图做文件IO,我写了一个程序:
我试图阅读的文字存储在名为 input.txt 的文件中。这是确切的文字......
I am a file.
This is a line.
This is the last line.
这是我阅读该文件并打印出我想要的结果的功能。
in1 = open("input.txt", 'r')
x=0
for line in in1:
print ('Line %d ' % (x)),
print ("(%d chars): " % (len(line))),
print (line),
x += 1
我的终端输出应
Line 0 (12 chars): I am a file.
Line 1 (15 chars): This is a line.
Line 2 (22 chars): This is the last line.
但我的实际终端输出是
Line 0 (13 chars): I am a file.
Line 1 (16 chars): This is a line.
Line 2 (22 chars): This is the last line.
当我的函数计算行的长度时,我相信它正在计算 Enter键我按下以便作为额外字符移动到下一行。我该如何解决这个问题?
答案 0 :(得分:5)
那是因为每一行都有一个你看不到的新行字符。请改用len(line.rstrip())
。