Q:

Reading from a file/split function new character line

f = open("test.txt", 'r+')
print ("Name of the file: ", f.name)
str = f.read();
str = str.split(',')

print(str2)

f.close()

I need to read from a file and it gives the name of the class it has to make and the parameters it needs to pass.
Example:
rectangle,9.7,7.3
square,6

so I have to make a rectangle object and pass those 2 parameters. then write it to another file with the results. I am stuck chopping up the string.
I use the split function to get rid of the commas, and it seems it returns a list which I am saving into the str list, which is probably bad, I should change the name. However, my concern is that although it does take the comma out. It keeps the ,\n, new line character and concatenates it to the next line. So it splits it like this ['rectangle', '9.7', '7.3\nsquare', ...
how can I get rid of that.
Any suggestions would be welcomed. Should I read line by line instead of reading the whole thing?

A:

Try calling strip() on each line to get rid of the newline character before splitting it.
Give this a try (EDIT - Annotated code with comments to make it easier to follow):
# Using "with open()" to open the file handle and have it automatically closed for your when the program exits.
with open("test.txt", 'r+') as f:
    print "Name of the file: ", f.name
    # Iterate over each line in the test.txt file
    for line in f:
        # Using strip() to remove newline characters and white space from each end of the line
        # Using split(',') to create a list ("tokens") containing each segment of the line separated by commas
        tokens = line.strip().split(',')
        # Print out the very first element (position 0) in the tokens list, which should be the "class"
        print "class: ", tokens[0]
        # Print out all of the remaining elements in the tokens list, starting at the second element (i.e. position "1" since lists are "zero-based")
        # This is using a "slice".  "tokens[1:]" means return the contents of the tokens list starting at position 1 and continuing to the end
        # "tokens[1:3]" Would mean give me all of the elements of the tokens list starting at position 1 and ending at position 3 (excluding position 3).
        # Loop over the elements returned by the slice, assigning them one by one to the "argument" variable
        for argument in tokens[1:]:
            # Print out the argument
            print "argument: ", argument

output:
Name of the file:  test.txt
class:  rectangle
argument:  9.7
argument:  7.3
class:  square
argument:  6

More information on slice:  http://pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/

