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
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:
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.
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.
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.
Code:
#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()
The only code I can come up with is the following:
Code:
f = open('migList.txt', 'r')#opens the file and sets it to read
Question 2: When I use integers in the list and try to save using the code above, I get the following error.
Code:
TypeError: sequence item 0: expected string, int found
I tried the following code which seemed to work.
Code:
migList[i] = str(migList[i])
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.
Comment