如何逐行读取文件并在Python中打印?

时间:2015-12-18 03:10:57

标签: python file

inputFile = open("pets.txt", 'r') # Makes File object
outputFile = open("results.csv", "w")
dictionary = {} # Our "hash table"
compare = "https://en.wikipedia.org/wiki/" # urls will compare against this string

for line in inputFile:
    lineToRead = inputFile.readline()
    # ---- testing ----
    print line # for some reason this prints the last line in pets.txt which is mouse
    print str(lineToRead) # for some reason this doesn't print the current line that was read
    print lineToRead
inputFile.close()

出于某种原因,打印的唯一内容是mouse。我的输入文件如下所示:

cat
dog
bird
mouse

我从未在Python中编程。

1 个答案:

答案 0 :(得分:1)

很好的尝试!

它实际上比你想象的更简单:

inputFile = open("pets.txt", 'r')
for line in inputFile:
    print line
inputFile.close()

这是因为Python在readline()循环的每次迭代中为您发出for

但是如果你想自己做,只是为了了解它是如何完成的呢?

inputFile = open("pets.txt", 'r')

lineToRead = inputFile.readline() # read the first line
print lineToRead

lineToRead = inputFile.readline() # read the second line
print lineToRead

lineToRead = inputFile.readline() # read the third line
print lineToRead

lineToRead = inputFile.readline() # read the fourth line
print lineToRead

inputFile.close()

试试吧!

当然,这仅在pets.txt只有4行的情况下才有效。为了改善这一点,您可以将该代码放在循环中:

inputFile = open("pets.txt", 'r')

lineToRead = inputFile.readline() # read the first line
print lineToRead

while "there's still lines to read":
    lineToRead = inputFile.readline() # read the following lines
    print lineToRead

inputFile.close()

有一点问题 - Python不明白你的意思是“仍然有阅读的行”。但是,如果您阅读the tutorial,您会注意到readline()在到达文档末尾时返回空字符串。所以:

inputFile = open("pets.txt", 'r')

lineToRead = inputFile.readline() # read the first line
print lineToRead

while lineToRead != '':
    lineToRead = inputFile.readline() # read the following lines
    print lineToRead

inputFile.close()

我希望你能跟着我。如果你不是,不要担心。继续尝试!