[英]How can I use nested for loops in Python-3.x to print from a text file one line at a time, x number of cycles?
[英]Print one line at a time from text file using python
好的,所以我傾倒了這個站點,但找不到任何有效的方法。 這是我的代碼
print("Type the filename")
file_again = raw_input("> ")
lines = [6]
with open(file_again, 'r') as f:
lines = f.read().splitlines()
for line in lines:
print line
但是我無法讓它逐行打印出來,而每行只能是一位數字。 我也想使用一個計數器,但是我無法正確使用該語法。 我嘗試枚舉,但對我來說效果不佳
print("Type the filename")
file_again = raw_input("> ")
with open(file_again, 'r') as f:
lines = f.readlines()
for num, line in enumerate(lines, 1):
print "%s: %s" % (num, line)
基本上,您有兩個問題:
readlines()
,它會返回列表中可以迭代的所有行。 enumerate()
將為您簡潔地在for
循環中提供一個計數器。 然后,格式化打印的行以顯示計數器和行值。 Python中的文件對象是迭代器。 因此,您可以直接遍歷它們:
from __future__ import print_function # get Python 3 printing in Python 2
with open(file_again) as fobj:
for lineno, line in enumerate(fobj, 1):
print('{}: {}'.format(lineno, line), end='')
end=''
不會在打印中添加換行符,因為每一行的末尾都已經有換行符。
這種方法的優點是您可以輕松處理大型文件,因為您無需一次讀取整個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.