Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading a text file
#1
I have a text file of letters on 8 different lines. I want to read through the file and print out the length of every 2nd line of that file and store it into a list.
for example the text file would look like :
"abcd"
"efgh"
"ijkl"
"mnop"
I am trying to have the output be [4,4]. It will only read every 2n line and store its length while ignoring the other lines. this is what i have so far.


def read_seq(file_name,num_seq):
    file=open(file_name,"r")
    file=file.read()
    count =0
    for x in file:
        print(x)
        count +=1
Reply
#2
you didn't use num_seq, so I removed it.
this one will start on line line 1 which is second line (n starts at 0)

def read_seq(file_name):
    with open(file_name, 'r') as f:
        mydata = f.readlines()
        for n, x in enumerate(mydata):
            if (n+1) % 2 == 0 and n != 0:
                print('{}, {}'.format(n, len(x)))

if __name__ == '__main__':
    read_seq('ziggy.txt')
Reply
#3
Another way to cound every second line

for num, line in enumerate(file_obj, 1):
    if num & 1: # check if num is odd
        pass
    else:
        print(len(line))
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
Just as a joke, but you can still learn about this.
Don't use this code.

with open(file_name) as fd:
    lineiterator = iter(fd)
    for line in lineiterator:
        print(line.strip())
        with contextlib.suppress(StopIteration):
            next(lineiterator)
fd is the file object.

The function iter(fd) makes an iterator from the file object.
This works only, when the file has been opened in text mode. Calling iter on a file object,
does the same what the for-loop does. The call next(lineiterator) jumps to the next line.
As you can see, there is no use of the returned data of next(lineiterator).
contextlib.suppress is just a context manager to suppress errors. In this case
StopIteration is suppressed. If this Exception StopIteration happend,
the end of file has been reached. The for-loop does get this Exception also and stops silently.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
How about: (using Python 3)

from itertools import islice
with open(file_name) as fd:
    alternatelines = islice(fd, 0, None, 2)
    for line in alternatelines:
        print(len(line.rstrip()))
Same principle as above, but uses islice from itertools to step through the file by 2 lines at a time. (I used rstrip on assumption that each line has a newline character at the end.)
I am trying to help you, really, even if it doesn't always seem that way
Reply
#6
Oh, yes. Your approach is much better :-)
Itertools is very powerful.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
gruntfutuk Wrote:How about: (using Python 3)
Now do itertools also work for Python 2,and i guess he use Python 3 bye his use of print function.
itertools.islice is cool @gruntfutuk,but for this i had gone for a more simplistic approach as shown in other post with enumerate.
with open('in.txt') as f:
    for count,line in enumerate(f, 1):
        if count % 2:
            print(len(line.strip()))
Reply
#8
(Oct-12-2017, 08:38 PM)snippsat Wrote:
gruntfutuk Wrote:How about: (using Python 3)
Now do itertools also work for Python 2,and i guess he use Python 3 bye his use of print function.
itertools.islice is cool @gruntfutuk,but for this i had gone for a more simplistic approach as shown in other post with enumerate.
with open('in.txt') as f:
    for count,line in enumerate(f, 1):
        if count % 2:
            print(len(line.strip()))

Your approach is best @snippsat, I was just trying to provide a simpler iter alternative to what @DeaD_EyE suggested as an approach. As the source file is so short, it is all pretty academic. Were the file large, we would be looking for the most efficient approach, avoiding reading anything we don't need to.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel File reading vanjoe198 1 2,005 Mar-31-2021, 11:53 AM
Last Post: snippsat
  Reading a text until matched string and print it as a single line cananb 1 1,997 Nov-29-2020, 01:38 PM
Last Post: DPaul
  reading from a file looseCannon101 14 4,750 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Convert text from an image to a text file Evil_Patrick 5 4,214 Jul-30-2019, 07:57 PM
Last Post: DeaD_EyE
  Weird problem with reading from file and performing calculations pineapple999 1 2,956 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Handling IO Error / Reading from file Expel 10 4,712 Jul-18-2019, 01:21 PM
Last Post: snippsat
  Reading an Unconventional CSV file OzSbk 2 3,829 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 10,241 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 3,369 May-24-2018, 12:12 PM
Last Post: sumit
  File Reading toxicxarrow 9 5,100 May-07-2018, 04:12 PM
Last Post: toxicxarrow

Forum Jump:

User Panel Messages

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