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

How do I import a list or array from a text file, manipulate it, then output it?

P: 39
I have written the following code that takes a list called migList, multiplies the strings by 5, then outputs it to a text file called migList.txt
Expand|Select|Wrap|Line Numbers
  1. #define a list called migList
  2. migList = ['cat', 'dog', 'car', '22']
  3.  
  4. #now add 5 to every unit in migList
  5.  
  6. for i in range(len(migList)):
  7.                migList[i] = migList[i]*5
  8.  
  9. fn = "migList.txt"
  10. f = open(fn,'w')
  11. f.write("\n".join(migList))
  12. f.close()
  13.  
Question 1: Now assuming that the list is in a text file, how do I parse in those values into a list that I can then manipulate and save to a text file?
The only code I can come up with is the following:
Expand|Select|Wrap|Line Numbers
  1. f = open('migList.txt', 'r')#opens the file and sets it to read
  2.  
After that, I'm stuck. I know I want to create a new list and then iterate over the items in the text file but I'm not quite sure how.

Question 2: When I use integers in the list and try to save using the code above, I get the following error.
Expand|Select|Wrap|Line Numbers
  1. TypeError: sequence item 0: expected string, int found
I believe I need to be writing a string to the file, and the command s = str(value) can be used but I'm not sure how to use that.
I tried the following code which seemed to work.
Expand|Select|Wrap|Line Numbers
  1. migList[i] = str(migList[i])
but is there a different way to do it? (I assume this is where pickle comes into play).
Again, thanks for your help, as my eventual goal is to learn enough about manipulating data in python to be able to manipulate some traffic data.
Dec 16 '10 #1

✓ answered by dwblas

readlines() will read the file into a list (assuming your file is not gigabytes in size). An overview of read and write.
Expand|Select|Wrap|Line Numbers
  1. f = open('migList.txt', 'r').readlines()
  2. for rec in f:
  3.     print f 

Share this Question
Share on Google+
2 Replies


Expert 100+
P: 621
readlines() will read the file into a list (assuming your file is not gigabytes in size). An overview of read and write.
Expand|Select|Wrap|Line Numbers
  1. f = open('migList.txt', 'r').readlines()
  2. for rec in f:
  3.     print f 
Dec 16 '10 #2

P: 39
That's a great first step but if I'm reading a simple file, i.e.
1
2
25
I get a list generated like so:
['1\n', '2\n', '25\n']
In order to use these values, I guess I have to clean up the list?
Dec 17 '10 #3

Post your reply

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