Python Forum
Printing lines in a basic text file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing lines in a basic text file
#1
I’ve got a basic text file. I am trying to print the 5th line (total 7 lines).

Here is my text file:
Quote:Welcome to your First Tribulation Recruit.
Only the best recruits can become agents.
Do you have what it takes?
We will test your knowledge with this field readiness exam.
It should be pretty simple, since you only know the basics so far.
Let's get started.
Best of luck recruit.

Here is my code with some annotations for readability:
# Opening the file as a variable
with open('field.txt') as field_variable:
    # Reading the file:
    field_variable = field_variable.readlines()
    # Turning it into a list:
    list(field_variable)
    # Splitting each line in the list:
    for i in field_variable:
        i.split()
    # Printing third line from the bottom by reverse slicing:
    print(field_variable[-3])
I am expecting this as the output:
Quote:It should be pretty simple, since you only know the basics so far.
That’s line 5.

And I actually do generate that output

Hooray! I won!

Ehm, not quite.

I wrote that code snippet myself but I only partially understand.

If you look at lines 8 and 9, how does the iterator (the ‘i’ aspect) in the for loop know to split each line? In my mind I’d figure that the the ‘i’ would go through every single individual character in the field_variable list. I don’t really understand this entirely.

Can someone here try to explain the logic of how the for loop knows to iterate through each line instead of each character?
Reply
#2
In your code, i would contain a line in your file. Thus its a string, and the string method split() would take 'i' in this case and by default it would return a list where it splits the line on whitespace characters.

Make a minor change:

for i in field_variable:
    print(i.split())
This will give you an idea of what split is doing here. In the end however you are printing the line correctly using a negative index of 3 in this case where you know its three lines from the bottom. Thus your for loop is not nessisary as your not using the output of i.split() in any way.
Reply
#3
you are doing something weird here. you use field_variable as a file pointer,
and then use it as your buffer. Not sure exactly how you get away with that, but expect it has to do with file buffering.
At any rate, it's not good.
here's how I would write that:
>>> from itertools import islice
>>> with open('field.txt') as fp:
...     print(list(islice(fp, 4, 5)))
... 
['It should be pretty simple, since you only know the basics so far.\n']
Reply
#4
This helps, @knackwurstbagel. My loop in its current form doesn’t actually do anything, as you’ve explained. But by modifying it slightly, also as you’ve suggested, it shows how the split function works. Here is the new output with your suggested modification:

Quote:['Welcome', 'to', 'your', 'First', 'Exam', 'Recruit.']
['Only', 'the', 'best', 'recruits', 'can', 'become', 'agents.']
['Do', 'you', 'have', 'what', 'it', 'takes?']
['We', 'will', 'test', 'your', 'knowledge', 'with', 'this', 'field', 'readiness', 'exam.']
['It', 'should', 'be', 'pretty', 'simple,', 'since', 'you', 'only', 'know', 'the', 'basics', 'so', 'far.']
["Let's", 'get', 'started.']
['Best', 'of', 'luck', 'recruit.']
It should be pretty simple, since you only know the basics so far.

I see now. The lines in the text file are split according to white space, not individual characters.

@Larz60+: Your code is elegant and far superior than mine. You mentioned buffering. I don’t really understand what you mean by file buffering and file pointers but it may have to do with the Jupyter Notebook tool that I’m doing this exercise with. You’ve done a terrific job re-writing my script on your own terms, but if I wanted to retain my somewhat novice approach while keeping my general awkward syntax, how would you modify my script to avoid making the mistake I made with the file-pointer buffer issue?
Reply
#5
Another possible solution, without itertools:

>>> with open('field.txt', 'r') as quotes:
...    for i, v in enumerate(quotes.readlines()):
...        if i == 4:
...            print(v)
...            break              # if line 5 reached you don't want iterate anymore
...
It should be pretty simple, since you only know the basics so far.
I should be pretty much in line with your original syntax.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
@perfringo: I really like your use of enumeration.

First you open the text file as a variable. Then for the two iterators inside the each line of the text file which you’ve declared, the first iterator, i, corresponds to each line. When i reaches line number 4, you print the other iterator, v. Then the operation is terminated.

A few days ago I was having difficulty grasping the concept of enumeration. There is a question on SO titled, “What does enumerate mean?” which has quite a number of answers explaining enumeration in general. It all went over my head when I was reading it a few days ago. But your use of enumeration is clear and easily understood in the context of printing line 5 in my text file. Thank you for the clarification, @perfringo.
Reply
#7
Just some point on @perfringo enumerate solution,can drop readlines() make a list unnecessary and just iterate over file object.
Can also set index to 1 in enumerate,then it will count normal as usually is wanted in lines of a file.
with open('field.txt') as f_obj:
    for index, line in enumerate(f_obj, 1):
        if index == 5:
            print(line.strip())
            break
Output:
It should be pretty simple, since you only know the basics so far.
To not have break can make function.
def foo():
    with open('field.txt') as f_obj:
        for index, line in enumerate(f_obj, 1):
            if index == 5:
                return line.strip()

print(foo())
Output:
It should be pretty simple, since you only know the basics so far.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,111 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Delete multiple lines from txt file Lky 6 2,281 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  python-docx: preserve formatting when printing lines Tmagpy 4 2,089 Jul-09-2022, 01:15 AM
Last Post: Tmagpy
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,653 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Editing text between two string from different lines Paqqno 1 1,311 Apr-06-2022, 10:34 PM
Last Post: BashBedlam
  failing to print not matched lines from second file tester_V 14 6,069 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Extracting Specific Lines from text file based on content. jokerfmj 8 2,952 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,949 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  raspberry use scrolling text two lines together fishbone 0 1,446 Sep-06-2021, 03:24 AM
Last Post: fishbone
  Importing a function from another file runs the old lines also dedesssse 6 2,541 Jul-06-2021, 07:04 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020