Reading a file and splitting at the same time

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Miguel Valenzue
    New Member
    • Dec 2010
    • 39

    Reading a file and splitting at the same time

    Is there a way to read and split it at the same time?
    I currently use this code.
    Code:
    chooseFile = raw_input ("Type File Name:")
    outputFile = raw_input ("Type File Output name with extension:")
    
    myfile=open(chooseFile,'r')
    myList =[]
    myList = myfile.readlines()
    
    splitList = []
    
    for i in myList:
        splitList.append (i.split(';'))
    It basically reads in a semicolon delimited file and splits it into a list.
    But I think there may be a more elegant way to do this.
    Last edited by Miguel Valenzue; Apr 25 '13, 09:26 AM. Reason: Adding more info
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You do not need to initialize the empty list "myList". If you create an open file object by assignment to an identifier, you should close it when you are done:myfile.close()
    "splitList" can be created using a list comprehension:
    Code:
    splitList = [line.split(";") for line in open(chooseFile).readlines()]

    Comment

    Working...