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.
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.
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.
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.