我怎样才能分隔csv中存在日期的那些行....例如

时间:2016-12-14 20:10:09

标签: python csv

I / P: -

1) 2/14/16, 7:19 PM - +91 9823547956: Hi all...
2) 24/14/16, 5:15 PM - +91 8026549795: have a good day
3) You might remember an interesting scene from there..
4) Many of us might find that example too difficult

我只需要日期为O / P的行: -

1) 2/14/16, 7:19 PM - +91 9823547956: Hi all...
2) 24/14/16, 5:15 PM - +91 8026549795: have a good day

2 个答案:

答案 0 :(得分:1)

如@ Jean-François所述,您的文件是一个简单的文本文件,它不是一个csv文件。要获得所需的输出,您可以尝试regex,如下所示:

import re

with open('out.txt', 'w') as out:
    with open('my_file.txt', 'r') as f:
        for line in f:
            if re.search('\d+\/\d+\/\d+', line):
                out.write(line)

现在,out.txt的内容是:

1) 2/14/16, 7:19 PM - +91 9823547956: Hi all...
2) 24/14/16, 5:15 PM - +91 8026549795: have a good day

使用with statement时,您无需显式关闭文件(通过调用file.close()),因为它会在块结束时自动完成。

答案 1 :(得分:0)

你需要的是正则表达式,

import re
re.search(r'\d+/\d+/\d+','The date is 11/12/98')

要在代码中加入,您可以这样做:

import re
new_file  = open('/new/file.csv','w+')

for line in open('/path/to/csv'):
    if re.search(r'\d+/\d+/\d+',line):
        new_file.write(line)