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 7604929
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T00:02:20+00:00 2026-05-31T00:02:20+00:00

For the following working code, I resorted to creating a class instance to store

  • 0

For the following working code, I resorted to creating a class instance to store the name variable of my file output [a_string] and the file object itself [f_object]. I found that variables assigned inside the first if statement did not appear in the scope inside the following elif statement.

#Text file splitter, data bewteen the '*' lines are copied into new files.

class Output_file():
    def __init__(self,a_string='none',f_object='none'):
        self.name=a_string
        self.foutput=f_object

outputfile=Output_file()

n=0
filehandle=open('original file.txt')
for line in filehandle:

    if line[0]=='*': #find the '*' that splits the rows of data
        n+=1
        outputfile.name = 'original file_'+str(n)+'.txt'
        outputfile.foutput= open(outputfile.name,'w')
        outputfile.foutput.write(line)

    elif len(line.split()) ==5 and n > 0: #make sure the bulk data occurs in blocks of 5
        outputfile.foutput= open(outputfile.name,'a+')
        outputfile.foutput.write(line)


outputfile.foutput.close()

Do I have to use a class instance to store the file name and object or is there a better way?

  • 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-05-31T00:02:22+00:00Added an answer on May 31, 2026 at 12:02 am

    Variables defined in either if or elif statement should appear in the other. For example:

    >>> for i in range(5):
    ...  if i%2==0:
    ...   x = i
    ...   print(x)
    ...  else:
    ...   print(x)
    ... 
    0
    0
    2
    2
    4
    

    This would not be the case in block-scoped languages, but unfortunately python is not block-scoped, and thus this should work.

    Do note however that for this to work, your name= must execute before you attempt to use it. That is, your if statement MUST execute at least once before your elif statement.

    Your code lacks comments, but I assume your data looks somewhat like:

     This is a header
     blah blah blah
     **************
     16 624 24 57 32
     352 73 47 76 3
     25 6 78 80 21 331
     **************
     234 234 4 64 7
     **************
     **************
     86 57 2 5 14
     4 8 3 634 7
    

    And you want to split them into separate files, but only if it’s “valid” data. I’d code it like so if I wanted to imitate your style:

    def isSeparatorLine(line):
        return line[0] = '*'
    def isValidLine(line):
        return len(line.split())==5
    
    groupNum = 0
    outputFile = None
    with open('original file.txt') as original:
        for line in original:
            if isSeparatorLine(line):
                groupNum += 1
                outputFilename = 'original file_{}.txt'.format(groupNum)
                if outputFile:
                    outputFile.close()
                outputFile = open(outputFilename, 'w')
                outputFile.write('New file with group {}'.format(groupNum))
            elif group>0 and isValidLine(line):
                outputFile.write(line)
    

    I’d however personally prefer to write it like so:

    from itertools import *
    
    FILENAME = 'original file.txt'
    FILENAME_TEMPLATE = 'stanza-{}.txt'
    
    def isSeparatorLine(line):
        return all(c=='*' for c in line)
    def isValidLine(line):
        return len(line.split())==5
    def extractStanzas(text):
        """
            Yields: [stanza0:line0,line1,...], [stanza1:lineN,lineN+1,...], [stanza2:...]
            where each stanza is separated by a separator line, as defined above
        """
        for isSeparator,stanza in groupby(text.splitlines(), isSeparatorLine):
            if not isSeparator:
                yield stanza
    
    with open(FILENAME) as f:
        stanzas = list(extractStanzas(f.read()))
    
    for i,stanza in enumerate(stanzas[1:]):
        assert all(isValidLine(line) for line in stanza), 'invalid line somewhere: {}'.format(stanza)
        with open(FILENAME_TEMPLATE.format(i), 'w') as output:
            output.write('\n'.join(stanza))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The following code is working great in a normal console application: private void button1_Click(object
I'm using the following working code to decrypt a file: #include <openssl/aes.h> #include <stdio.h>
I'm trying to get the following code working: string url = String.Format(@SOMEURL); string user
On a Solaris 5.8 machine, I have the following code: [non-working code] char *buf;
Why is the following code not working? if(EventLog.Exists(Foo)) { EventLog.Delete(Foo); } if(EventLog.Exists(Foo) == false)
Why isn't the following piece of code working in IE8? <select> <option onclick=javascript: alert('test');>5</option>
can anybody tell me why is the following code not working? <script type=text/javascript src=../../Scripts/jquery.js></script>
i am using python 2.5.2 . The following code not working. def findValue(self, text,
Working with the following code, I need to return only records where the `point'
I am working on the following code: import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import

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.