Python:读写带有标题和数字列的文本文件

2024-10-01 13:39:35 发布

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

我有一个文本文件,它有一些标题行和一些列(数字)。 我想跳过标题来阅读这个文件,然后选择一些列并 使用Python脚本在新文件中编写它们。在

例如,让我们调用in_table.txt下面的数据。 我想跳过页眉(也就是空白行), 然后选择第一列和第四列(仅限数值) 并将它们保存在一个新文件out_table.txt中,没有标题,只有数字。 如何使用Python脚本实现这一点?在

非常感谢!!在

在_表格.txt公司名称:

hline1 hline1 hline1
hline2 hline2 hline2

hline3 hline3 hline3

par1  par2  par3  par4  par5
1.    10.   100.  1000. 10000.
2.    20.   200.  2000. 20000.
3.    30.   300.  3000. 30000.
4.    40.   400.  4000. 40000.
5.    50.   500.  5000. 50000.

一。在


Tags: 文件数据intxt脚本标题table数字
1条回答
网友
1楼 · 发布于 2024-10-01 13:39:35

如果您坚持使用空格分隔符,请使用

with open('in_table.txt') as f:
    # Iterate through the file until the table starts
    for line in f:
        if line.startswith('   '):
            break
    # Read the rest of the data, using spaces to split. 
    data = [r.split() for r in f]

with open('out_file.csv', 'w') as of:
    for r in data:
        # Write only column 0 and 2 (re: 0-indexing)
        of.write('%s, %s\n'%(r[0], r[2]))

CSV

如果你用逗号分隔,你很可能会在csv库中内置Python

^{pr2}$

或者更简洁一点

import csv 
with open('in_table.txt') as f:
    for line in f:
        if line.startswith('   '):
            break  
    data = [r[0]+r[2] for r in csv.reader(f)]

wrt = csv.writer(open('out_file.csv', 'w'))
wrt.writerows(data)

相关问题 更多 >