Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8858779
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T14:54:23+00:00 2026-06-14T14:54:23+00:00

I am doing text processing and using ‘readline()’ function as follows: ifd = open(…)

  • 0

I am doing text processing and using ‘readline()’ function as follows:

ifd = open(...)
for line in ifd:
   while (condition)
         do something...
         line = ifd.readline()
         condition = ....

#Here when the condition becomes false I need to rewind the pointer so that the ‘for’ loop read the same line again.

ifd.fseek() followed by readline is giving me a ‘\n’ character. How to rewind the pointer so that the whole line is read again.

>>> ifd.seek(-1,1)
>>> line = ifd.readline()
>>> line
'\n'

Here is my code

labtestnames = sorted(tmp)
#Now read each line in the inFile and write into outFile
ifd = open(inFile, "r")
ofd = open(outFile, "w")
#read the header
header = ifd.readline() #Do nothing with this line. Skip
#Write header into the output file
nl = "mrn\tspecimen_id\tlab_number\tlogin_dt\tfluid"
offset = len(nl.split("\t"))
nl = nl + "\t" + "\t".join(labtestnames)
ofd.write(nl+"\n")
lenFields = len(nl.split("\t"))


print "Reading the input file and converting into modified file for further processing (correlation analysis etc..)"

prevTup = (0,0,0)
rowComplete = 0
k=0
for line in ifd:
    k=k+1
    if (k==200): break

    items = line.rstrip("\n").split("\t")
    if((items[0] =='')):
        continue
    newline= list('' for i in range(lenFields))
    newline[0],newline[1],newline[3],newline[2],newline[4] = items[0], items[1], items[3], items[2], items[4]
    ltests = []
    ltvals = []
    while(cmp(prevTup, (items[0], items[1], items[3])) == 0): # If the same mrn, lab_number and specimen_id then fill the same row. else create a new row.
        ltests.append(items[6])
        ltvals.append(items[7])
        pos = ifd.tell()
        line = ifd.readline()
        prevTup = (items[0], items[1], items[3])
        items = line.rstrip("\n").split("\t")
        rowComplete = 1

    if (rowComplete == 1): #If the row is completed, prepare newline and write into outfile
        indices = [labtestnames.index(x) for x in ltests]
        j=0
        ifd.seek(pos)
        for i in indices:
            newline[i+offset] = ltvals[j]
            j=j+1

    if (rowComplete == 0): # 
        currTup = (items[0], items[1], items[3])
        ltests = items[6]
        ltvals = items[7]
        pos = ifd.tell()
        line = ifd.readline()
        items = line.rstrip("\n").split("\t")
        newTup = (items[0], items[1], items[3])
        if(cmp(currTup, newTup) == 0):
            prevTup = currTup
            ifd.seek(pos)
            continue
        else:
            indices = labtestnames.index(ltests)
            newline[indices+offset] = ltvals

    ofd.write(newline+"\n")
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T14:54:24+00:00Added an answer on June 14, 2026 at 2:54 pm

    The problem can be handled more simply using itertools.groupby. groupby can cluster all the contiguous lines that deal with the same mrn, specimen_id, and lab_num.

    The code that does this is

    for key, group in IT.groupby(reader, key = mykey):
    

    where reader iterates over the lines of the input file, and mykey is defined by

    def mykey(row):
        return (row['mrn'], row['specimen_id'], row['lab_num'])
    

    Each row from reader is passed to mykey, and all rows with the same key are clustered together in the same group.


    While we’re at it, we might as well use the csv module to read each line into a dict (which I call row). This frees us from having to deal with low-level string manipulation like line.rstrip("\n").split("\t") and instead of referring to columns by index numbers (e.g. row[3]) we can write code that speaks in higher-level terms such as row['lab_num'].


    import itertools as IT
    import csv
    
    inFile = 'curious.dat'
    outFile = 'curious.out'
    
    def mykey(row):
        return (row['mrn'], row['specimen_id'], row['lab_num'])
    
    fieldnames = 'mrn specimen_id date    lab_num Bilirubin   Lipase  Calcium Magnesium   Phosphate'.split()
    
    with open(inFile, 'rb') as ifd:
        reader = csv.DictReader(ifd, delimiter = '\t')
        with open(outFile, 'wb') as ofd:
            writer = csv.DictWriter(
                ofd, fieldnames, delimiter = '\t', lineterminator = '\n', )
            writer.writeheader()
            for key, group in IT.groupby(reader, key = mykey):
                new = {}
                row = next(group)
                for key in ('mrn', 'specimen_id', 'date', 'lab_num'):
                    new[key] = row[key]
                    new[row['labtest']] = row['result_val']                
                for row in group:
                    new[row['labtest']] = row['result_val']
                writer.writerow(new)
    

    yields

    mrn specimen_id date    lab_num Bilirubin   Lipase  Calcium Magnesium   Phosphate
    4419529 1614487 26.2675 5802791G    0.1             
    3319529 1614487 26.2675 5802791G    0.3 153 8.1 2.1 4
    5713871 682571  56.0779 9732266E                    4.1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My particular scenario involves doing some text transformation using regular expressions within a private
I am writing a python script that will be doing some processing on text
In C# 3.5 System.Speech.dll was added for doing text-to-speech and speech-to-text conversions. Searching on
im doing research project for a the game Text twist,the text will automatically search
Currently I am doing this: I have text that looks like: Hello ${user.name}, this
I'm doing some personal research into text analysis, and have come up with close
Im doing something quite specific where I have a text input, I want to
I am doing a project in which i am designing a Text Editor application
Im doing a project with C# winforms. This project is composed by: alt text
I am doing internationalisation in django admin.I am able to convert all my text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.