Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

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
Quote
#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')
Quote
#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
Quote
#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.
My code examples are always for Python 3.x.
All humans together. We don't need politicians!
Quote
#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.)
Larz60+ and DeaD_EyE like this post
I only use Python 3 (except where stated otherwise)
If you are not confused, you are misinformed
Quote
#6
Oh, yes. Your approach is much better :-)
Itertools is very powerful.
gruntfutuk likes this post
My code examples are always for Python 3.x.
All humans together. We don't need politicians!
Quote
#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()))
buran likes this post
Quote
#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 only use Python 3 (except where stated otherwise)
If you are not confused, you are misinformed
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Reading string groups of 3. fivestar 2 56 Oct-15-2017, 04:03 PM
Last Post: fivestar
  Cannot read from text file aljonesy 5 87 Oct-05-2017, 05:56 PM
Last Post: nilamo
  program that search string in text file and do something alon30 1 114 Aug-04-2017, 08:10 AM
Last Post: buran
  text = str(text.encode('utf-8')) AttributeError: 'float' object has no attribute 'enc ulrich48155 2 266 Jul-31-2017, 05:21 PM
Last Post: ulrich48155
  Parse text from a .txt file and save multiple output .txt rattlerskin 9 756 Mar-17-2017, 01:45 PM
Last Post: Larz60+
  Class for reading a csv FIie Ambriador 3 423 Jan-29-2017, 05:41 PM
Last Post: Ofnuts
  How to extract two data types from a text file and store them as two separate lists banf 1 395 Jan-16-2017, 09:52 PM
Last Post: Larz60+
  Dictionary + File Reading palmtrees 2 535 Nov-15-2016, 05:16 PM
Last Post: Ofnuts

Forum Jump:


Users browsing this thread: 1 Guest(s)