首页 > 解决方案 > python strip方法在csv文件中不起作用

问题描述

我有一个 csv 文件转置,当在记事本中打开时,它看起来如下

电话号码,1234,,,

door_number,abcd,,,

名称,abcd,efgh,ijkl,mnop

下面是我的代码

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

打印(行)

但是,它不会从 csv 中删除最后一个逗号。我必须在其他应用程序中使用数据。这需要这种格式。另外,我只希望第一个分隔符为“,”,其余为“;” 可能吗?

标签: python-3.x

解决方案


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.


推荐阅读