【问题标题】:When writing section of txt-file to csv, each single character is assigned a new column for each line将 txt 文件的部分写入 csv 时,每行为每个单个字符分配一个新列
【发布时间】:2018-07-12 18:55:19
【问题描述】:

我编写了一个程序,它读取文本文件的所有行,然后找到行中特定字符串以 Kbits 结尾的部分。对于发生这种情况的所有行,我将 Kbits 之前的部分(它是一个 int)放入一个列表中,然后我将其写入一个 csv 文件。问题是,当我写入 csv 文件时,Int 被拆分,每个数字都分配给 csv 文件中的一个新列。我有一个想法与我的打字方式有关,但我无法弄清楚。 我正在使用 Python 2.7。

txt 文件中的一行是这样的:

[2018-01-24 14:57:05,766] [  5]   2.00-3.00   sec   872 KBytes  7140 Kbits/sec  2.714 ms  693/1326 (52%) 

对于这个特定的行,我想在我的 .csv 文件中有一个 7140

我的代码如下:

lst = []
myfile = file('file.csv', 'wb')
txtfile = open('file.txt')

for line in txtfile:
    line = str(re.findall('\d*\ Kbits', line))
    if(line == "[]"):
        r = 1
    else:
        new = line.replace(" Kbits", "")
        lst.append(new)

wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
for i in range(0, len(lst)):
    wr.writerow(lst[i])
txtfile.close()

【问题讨论】:

  • 您能否在.csv 文件中提供一些输入字符串以及您想要的内容?只需编辑问题。

标签: python regex csv


【解决方案1】:

尝试以下方法:

import re
import csv

with open('file.txt', 'rb') as f_input, open('file.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, quoting=csv.QUOTE_ALL)

    for row in f_input:
        kbits = re.findall('(\d+)\ Kbits', row)

        if kbits:
            csv_output.writerow(kbits)

对于您的示例行 file.csv 看起来像:

"7140"

【讨论】:

  • 我也可以得到那个输出,当我只想要数字部分时会出现问题。所以我想要的不是“7140 Kbits”,而是“7140”,还要注意完整的 .txt 文件中的某些行不包含“Kbits”的行。
  • 你只需要使用(\d+),我已经更新了脚本。
  • 谢谢你,成功了。我想我可能一开始就把这件事复杂化了。
猜你喜欢
  • 2021-08-31
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
相关资源
最近更新 更多