在python中读取文件时行号不匹配

2024-04-25 03:30:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的剧本如下:

counter = 0
with open(output_file, 'a') as f_out:
    with codecs.open(data_file, 'r', encoding='utf8') as f:
        for line in f:
            counter += 1
            try:
                created_at = datetime.strptime(line[:first_colon], '%Y-%m-%d').strftime('%Y-%m-%d')
            except ValueError:
                log('Parse Error at line ' + str(counter))
                continue
            f_out.write(str(counter)+','+line+'\n')

当我使用

sed -n '#counterhere#p' data_file

,我发现行不匹配。你知道吗

你知道这里发生了什么吗?你知道吗

编辑:

例如,在数据文件中,我们有:

2016-03-18,Content1
2016-03-#J,Content2
2016-03-20,Content3

因此,在输出文件中,我们有:

1,2016-03-18,Content1
3,2016-03-20,Content3

这样我就可以在数据文件中找到精确的行,使用如下方法:

sed -n '3p' data_file

如果没有,它应该返回“Content3”

在小文件中,一切都很顺利。但是因为我在大文件上运行它,所以我很难调试它。你知道吗


Tags: 文件data数据文件aswithlinecounteropen
1条回答
网友
1楼 · 发布于 2024-04-25 03:30:21

下面是我一直在使用的工作示例:

import codecs
from datetime import datetime

output_file = 'out.csv'
data_file = 'data.csv'
first_colon = 9

counter = 0
with open(output_file, 'a') as f_out:
    with codecs.open(data_file, 'r', encoding='utf8') as f:
        for line in f:
            counter += 1
            try:
                created_at = datetime.strptime(line[:first_colon], '%Y-%m-%d').strftime('%Y-%m-%d')
            except ValueError:
                print('Parse Error at line ' + str(counter))
                continue
            f_out.write(str(counter)+','+line)

使用data.csv文件:

2016-03-18,Content1
2016-03-#J,Content2
2016-03-20,Content3

给出out.csv

1,2016-03-18,Content1
3,2016-03-20,Content3

它具有data.csv中正确源行的正确行号。因此,这些行号可用于查找源文件中的信息:

sed -n '3p' data.csv

给了我

2016-03-20,Content3

希望这有助于推动事情向前发展。你知道吗

相关问题 更多 >