0

How to open three files which have same sequence of data inside, and all these file data should run inside a loop. That loop will capture the values inside the file. First read first file data and then second file then third. How can make this work in my existing code...

def memberStatus():
 inputFile = open('Members.txt', 'r')
 inputFile = open('Members1.txt', 'r')
 inputFile = open('Members2.txt', 'r')
 with inputFile as myFile:
    for number, line in enumerate(myFile):
        line=(line.rstrip()).split()
        rawList=[]
        rawList.append(line)
        print("raw list : ", rawList)
        intLine1 = [str(elem) for elem in rawList]
        intLine1 = ''.join(intLine1)
        AgeItem = intLine1[2:4]
        winLoosItem = intLine1[8:9]
        logInItem = intLine1[13:16]
        GenderItem = intLine1[20:26]
        incomeItem = intLine1[30:33]

These're the three files which should run inside "with inputFile as myFile:" loop

  • Members.txt
  • Members1.txt
  • Members2.txt

2 Answers 2

2

With doing that:

inputFile = open('Members.txt', 'r')
inputFile = open('Members1.txt', 'r')
inputFile = open('Members2.txt', 'r')

You simply reassign the inputFile name to other file each time.

One of many possible ways to go would be for example to put names of files to the list and then iterate through the list.

 inputFiles = ['Members.txt', 'Members1.txt', 'Members2.txt']
 for membersFile in inputFiles:
     myFile = open(membersFile, 'r')
     # And rest of code goes in here.
     myFile.close()

Edit: @SergeBallesta is right that you would normally rather use the with statement for operations on files as it's very convenient and simple to use and in this example it would like this:

 inputFiles = ['Members.txt', 'Members1.txt', 'Members2.txt']
 for membersFile in inputFiles:
     with open(membersFile, 'r') as myFile:
         # And rest of code goes in here.

One should probably decide on his own what seems more convenient for him and his/her eyes.

Sign up to request clarification or add additional context in comments.

3 Comments

with open(membersFile, 'r') as myFile: would at least ensure a clean close of each file between trying to process next...
@SergeBallesta True, however all you have to do is use the close method at the end of iteration and with using the with statement you create additional indentation level and sacrificing readability imo is not really worth it in such simple case.
Thankyou @Peter Nimroot it's work.. and I'm feeling I'm so stupid that I didn't notice that simple solution. Thankyou
2
def memberStatus():
  for name in ['Members.txt', 'Members1.txt', 'Members2.txt']:
    with open(name, 'r') as myFile:
      # do stuff

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.