简体   繁体   中英

Print one line at a time from text file using python

ok so I've poured over this site and I CAN'T find anything that works. here is my code

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 

BUT I can't get it to print out line by line and all it would be is one digit in each line. I'd also like to use a counter but I can't get that syntax right. i tried enumerating but that didnt work out well for me

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) 

Basically, you had two issues:

  1. You need to loop over the lines. For this, use readlines() , which returns all the lines in a list you can iterate through.
  2. You need to print a counter and the line value. For this, enumerate() will provide you a counter in the for loop concisely. Then, format the printed line to show both the counter and the line value.

File objects in Python are iterators. So you can iterate over them directly:

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='')

The end='' does not add a newline to the print because each line has a newline at its end already.

The advantage of this approach is that you can easily work with large files because you don't need to read the whole file at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM