Strip method does not work on lines from a file

Question:

I have a csv file transposed and when opened in notepad, it looks like below

phone_number,1234,,,
door_number,abcd,,,
name,abcd,efgh,ijkl,mnop

below is my code:

with open("test.csv") as f:
    for line in f:
       (line.strip(','))
        print(line)

However, it does not strip last commas from the csv.

Asked By: Prashanth

||

Answers:

Consider this string in Python:

>>> line='123,n'

The n is invisible unless you print a representation of it:

>>> print(line)
123,

>>> print(repr(line))
'123,n'

So it is easy to forget it is there.

But .strip(character) only works on the last charter. If you do this:

>>> line.strip(',')
'123,n' 

The comma is not removed. You have to take off the n first, then the , and then reassign the new string back to line:

>>> line=line.rstrip().rstrip(',')
>>> line
'123'

And, as Kevin mentions in comments, that only changes the string — not the file. To do that, you need to open a different file that can be written to, write your changes, then copy the new file on top of the old file.

Answered By: dawg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.