【问题标题】:Split Column in txt file in PythonPython中的txt文件中的拆分列
【发布时间】:2017-10-20 12:33:26
【问题描述】:

我是python的初学者。我用 python 2.7.11 制作了一个小脚本来从安捷伦设备获取数据,但格式并不理想。 到目前为止,我已经成功地将我的数据格式化为一个 txt 文件:

频率1

频率2

...

频率201

数据1

数据2

...

数据201

我想将它们格式化如下,以便我可以轻松地用 excel 打开 txt 文件:

频率1;数据1

频率2;数据2

... ; ...

频率201;数据201

您知道实现这一目标的任何简单方法吗?

提前致谢

CL

【问题讨论】:

  • 是否有一对一的映射,并且保证有 N 行频率,然后有 N 行数据?如果是这样,您可以将文件加载到内存中 - 然后您可以将其分成两部分并将它们压缩在一起
  • 是的,95% 的测量将有 201 行频率和 201 行数据。如何将文件加载到内存中,将其拆分并压缩回来?我可以使用“;”吗将列压缩在一起的字符?

标签: python-2.7 multiple-columns


【解决方案1】:

由于你的频率行数和数据行数相同,这段代码应该可以解决问题:

#imports OrderedDict to have an Ordered dictionary
from collections import OrderedDict

#opens files
my_file = open('freq.txt','r')
my_new_file = open("new.txt",'w')

#saves lines of file as a list, with each line being one item in the list
lines_list = my_file.readlines()

#creates empty dictionary to fill with data
freq_data = OrderedDict()

#iterates through lines and adds to dictionary, with freq as key and data as value
for line in range(len(lines_list)/2):
    freq_data[lines_list[line]] = lines_list[line+10]
    keys = freq_data.keys()

#writes to your new file
for i in keys:
    my_new_file.write(i.strip() + ' ; ' + freq_data[i])

#closes both files
my_file.close()
my_new_file.close()

基本上这段代码的作用是打开您的文件,将每个频率连接到相应的数据值,然后将其写入新文件。你可以换行

freq_data[lines_list[line]] = lines_list[line+10]

到你的数据除以二的任何数量的行,所以对你来说它会是

freq_data[lines_list[line]] = lines_list[line+201]

这会将文本文件变成如下所示:

频率1 频率2 频率3 ... 数据1 数据2 数据3

... 进入

频率1;数据1

频率2;数据2

频率3;数据3 ...

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2021-07-15
    相关资源
    最近更新 更多