python-3.x - 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 中删除最后一个逗号。我必须在其他应用程序中使用数据。这需要这种格式。另外,我只希望第一个分隔符为“,”,其余为“;” 可能吗?
解决方案
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.
推荐阅读
- php - Mysql查询执行失败
- bash - 如何在一行中找到 ip 并将其替换为 bash 脚本?
- django - perform_create 后 Django 回滚事务
- android - 没有订阅者在 EventBus 中的片段之间注册事件类
- html - HTML Ajax将选择选项转换为按钮不发送参数
- node.js - 有没有办法在快递 res.json() 之后重定向到另一条路线?
- recursion - f(n-1) + f(n-2) 如何一起调用 f(n)?
- crystal-reports - 如何将总结信息打印到报告中
- node.js - 无法用链接包装 Menu.Item
- git - 不能 git add 。它显示警告:无法打开目录