在提取两个关键字之间的数据时,Python输出提供字节而不是字符串

2024-09-29 22:42:22 发布

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

A具有以下代码:

import re
import csv
import time

print(time.ctime())

input_name = r"C:\Users\npatel\Documents\Coremotion 
Data\MotionData\data_file.csv"
output_name = r"C:\Users\npatel\Documents\Coremotion 
Data\MotionData\output_file.csv"

with open(input_name, 'r') as f_input, open(output_name, 'w') as f_output:
# Read whole file in
all_input = f_input.read()  

# Extract interesting lines
ab_input = re.findall(r'start(.*?)stop', all_input, re.DOTALL)[0]

csv_input = csv.reader(ab_input)
csv_output = csv.writer(f_output)


for input_row in csv_input:
    # Skip any empty rows
    if input_row:
        # Write row at a time to the output
        csv_output.writerows(input_row)

        print(input_row)

我试图提取开始和停止之间的数据,但它提取单个字节。它将所有字母和数字从一个单词或浮点数中分离出来。输出为:

 Tue Nov 21 10:35:33 2017
  ['2']
  ['0']
  ['1']
  ['7']
  ['-']
  ['1']
  ['1']
  ['-']
  ['1']
  ['3']

  ['', '']
  ['m']
  ['o']
  ['t']
  ['i']

Tags: csvnameimportreinputoutputdatatime
1条回答
网友
1楼 · 发布于 2024-09-29 22:42:22

你知道吗csv.reader文件不是合适的工具。你知道吗

Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

所以在你的例子中,它在字符串上迭代。你知道吗

尝试将csv_input = csv.reader(ab_input)替换为像csv_input = ab_input.split(',')这样更简单的内容。这将为您提供该CSV行上的值列表。你知道吗

相关问题 更多 >

    热门问题