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

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

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

    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
    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()
    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:
    Code:
    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.
    Code:
    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.
    Code:
    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.
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    readlines() will read the file into a list (assuming your file is not gigabytes in size). An overview of read and write.
    Code:
    f = open('migList.txt', 'r').readlines()
    for rec in f:
        print f

    Comment

    • Miguel Valenzue
      New Member
      • Dec 2010
      • 39

      #3
      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?

      Comment

      Working...