By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,689 Members | 1,110 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,689 IT Pros & Developers. It's quick & easy.

Reading a file and splitting at the same time

P: 39
Is there a way to read and split it at the same time?
I currently use this code.
Expand|Select|Wrap|Line Numbers
  1. chooseFile = raw_input ("Type File Name:")
  2. outputFile = raw_input ("Type File Output name with extension:")
  3.  
  4. myfile=open(chooseFile,'r')
  5. myList =[]
  6. myList = myfile.readlines()
  7.  
  8. splitList = []
  9.  
  10. for i in myList:
  11.     splitList.append (i.split(';'))
  12.  
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.
Apr 25 '13 #1

✓ answered by bvdet

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:
Expand|Select|Wrap|Line Numbers
  1. splitList = [line.split(";") for line in open(chooseFile).readlines()]

Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
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:
Expand|Select|Wrap|Line Numbers
  1. splitList = [line.split(";") for line in open(chooseFile).readlines()]
Apr 25 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.