0

I have a csv file transposed and when opened in notepad, it looks 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. I have to use the data in some other application. which requires this format. Also, I want only the first delimiter to be "," and rest to be ";" is it possible?

Prashanth
  • 29
  • 5
  • 3
    Likely this is because there is a `\n` to the right of the the `,` and the end of the line. Try `line=line.rstrip().rstrip(',')` – dawg May 07 '20 at 15:28
  • Also keep in mind that calling `rstrip()` on `line` will have no effect on the contents of the file, even if you assign the result back to `line` as dawg has done. If you need to alter a file, you can't do that just by opening it in read mode. – Kevin May 07 '20 at 15:34
  • Hi Kevin, in this case do I need to write back the contents again back to file? – Prashanth May 07 '20 at 16:06

1 Answers1

1

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.

dawg
  • 90,796
  • 20
  • 120
  • 197
  • Read [this SO post](https://stackoverflow.com/questions/125703/how-to-modify-a-text-file) on how to modify a txt file in Python. – dawg May 07 '20 at 16:12