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
-
#define a list called migList
-
migList = ['cat', 'dog', 'car', '22']
-
-
#now add 5 to every unit in migList
-
-
for i in range(len(migList)):
-
migList[i] = migList[i]*5
-
-
fn = "migList.txt"
-
f = open(fn,'w')
-
f.write("\n".join(migList))
-
f.close()
-
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:
-
f = open('migList.txt', 'r')#opens the file and sets it to read
-
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.
- 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.
- 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.