【问题标题】:Recorded ECG data into text file将心电图数据记录到文本文件中
【发布时间】:2019-11-19 10:10:55
【问题描述】:

我拥有的原始心电图是 csv 格式的。我需要将其转换为只有心电图数据的 .txt 文件。我需要一个相同的python代码。我能得到一些帮助吗?

csv_file = 'ECG_data_125Hz_Simulator_Patch_Normal_Sinus.csv'
txt_file = 'ECG_data_125Hz_Simulator_Patch_Normal_Sinus.txt'
import csv
with open(txt_file, "w") as my_output_file:
    with open(csv_file, "r") as my_input_file:
        //need to write data to the output file
    my_output_file.close()

输入的心电图数据如下所示: Raw_ECG_data

【问题讨论】:

  • .csv 文件实际上是一个.txt 文件。只是重命名。我认为您想要的是在.csv 文件中选择和过滤一列。
  • 我看过那个链接。 join 包括这两个数据。我检查了 python 文档,我没有找到一个合适的函数来只包含特定的数据。
  • @MEdwin,是的,这正是我想要做的。
  • 好的,下面已经回答了。您基本上可以使用@asif 的代码并将带有join(row) 的部分更改为join(row[2])。这意味着您正在将原始文件中的第 3 列过滤到输出 txt 文件中。让我知道它是否有效。

标签: python


【解决方案1】:

什么对我有用

import csv
csv_file = 'FL_insurance_sample.csv'
txt_file = 'ECG_data_125Hz_Simulator_Patch_Normal_Sinus.txt'
with open(txt_file, "w") as my_output_file:
    with open(csv_file, "r") as my_input_file:
        [ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
    my_output_file.close()

【讨论】:

  • 我试过@Asif给出的代码。 join(row[2]) 导致超出索引错误。 join(row[1]) 导致空白 .txt 文件。而 join(row[0]) 给出了不需要的列数据。
  • @Jasmine 如果输入 csv 与您指定的相同,它应该可以工作。你能上传你的csv并指定你想要的确切输出吗?帮助很容易
  • [![所需的 .txt 文件][1]][1],这是所需的输出 [![原始心电图数据][2]][2] [1]:@ 987654321@[2]:i.stack.imgur.com/CWJus.png
【解决方案2】:

一些事情:

  • 您可以使用同一个上下文管理器打开多个文件(with 语句):
with open(csv_file, 'r') as input_file, open(txt_file, 'w') as output_file:
    ...
  • 当使用上下文管理器处理文件时,不需要关闭文件,这就是with 语句所做的;它的意思是“打开文件,执行以下操作”。因此,一旦块结束,文件就会关闭。

  • 可以执行以下操作:

with open(csv_file, 'r') as input_file, open(txt_file, 'w') as output_file:
    for line in input_file:
        output_file.write(line)

...但正如@MEdwin所说,csv可以重命名,逗号将不再充当分隔符;它只会变成一个普通的 .txt 文件。您可以在 python 中使用os.rename() 重命名文件:

import os

os.rename('file,txt', 'file.csv')
  • 最后,如果你想在写入txt文件时从csv中删除某些列,你可以使用.split()。这允许您使用诸如逗号之类的标识符,并将根据此标识符的行分隔为字符串列表。例如:
"Hello, this is a test".split(',')
>>> ["Hello", "this is a test"]

然后您可以将列表中的某些索引写入新文件。

有关删除列的更多信息,see this post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 2020-03-11
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    相关资源
    最近更新 更多