在python中使用csv.reader时如何使用多个分隔符? [英] How to use multiple delimiters when using csv.reader in python?

查看:2085
本文介绍了在python中使用csv.reader时如何使用多个分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中有多行文本,看起来像这样:

I have multiple lines of texts in a text file that look similar to this:

2012-03-16 13:47:30.465 -0400   START  Running    Lab.script    19    on_the

我想要能够转换这段文字文件到csv。我已经使用这个代码:

I want to be able to convert this text file into csv. I've already done that using this code:

fin = csv.reader(open('LogFile.txt', 'rb'), delimiter='\t')
fout = open('newLogFile.csv', 'w')
for row in fin:
   fout.write(','.join(row) + '\n')

但是现在我的问题是,可以在此部分行中的空格后面添加,:

But now, my issue is that I need to be able to add a "," after the spaces in this part of the line:

2012-03-16 13:47:30.465 -0400 



我不知道该怎么做,我试过使用split ),拆分当前行/位置,但它没有工作。任何建议都会非常有帮助。

I'm not sure how to do it, I've tried using split(), to split the current row/position but it didn't work. Any suggestions would be very helpful.

谢谢

推荐答案

有帮助,而只是从一开始就从tab分隔一切?如果是,您可以参考此 answer ,实质上

Would helpful to instead just tab delimit everything from the beginning? If so you can refer to this answer, essentially


对于这个用例,有一个特殊的快捷方式!

There is a special-case shortcut for exactly this use case!

如果你调用str.split没有参数, b $ b空格而不是单个字符。所以:

If you call str.split without an argument, it splits on runs of whitespace instead of single characters. So:

>>> ' '.join("Please \n don't \t hurt \x0b me.".split()) 
"Please don't hurt me."


b

newLogFile = open('newLogFile.csv', 'w')
textFile = open('LogFile.txt', 'rb')
for row in textFile:
    newLogFile.write('\t'.join(row.split()))

您也说过


但现在,我的问题是我需要能够添加,在此部分的
空格后:

But now, my issue is that I need to be able to add a "," after the spaces in this part of the line:

2012-03-16 13:47:30.465 -0400

2012-03-16 13:47:30.465 -0400

给我听起来像你想要的

2012-03-16 ,13:47:30.465 ,-0400

这篇关于在python中使用csv.reader时如何使用多个分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆