从文件中仅读取一行并在Python中分割

2024-03-28 16:17:57 发布

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

我有一个ASCII文件,格式如下:

a = 20.0
b = 30.0
c = 30.0
h3    p1   p2 p3 p4    p5
000  000  000 22 00    000
...
.
.
.

我只想读第四行的名字。我试过了:

1)打开行,然后拆分:

# Reading 'data.txt'
line = open('data.txt', 'r')
line_i = line.readlines()[3]
line.close()

line_i = line_i.split(' ')
print line_i

输出:

['h3', '', '', '', 'p1', '', '', 'p2', 'p3', 'p4', '', '', '', 'p5\n']

(二)

import csv
line = open('data.txt', 'r')
line_i = line.readlines()[3]
line.close()

line_i = csv.reader(line_i,delimiter=' ')
print line_i

输出:

<_csv.reader object at 0x205e7c0>

如何做到这一点?你知道吗


Tags: csvtxtclosedatalineopenh3reader
1条回答
网友
1楼 · 发布于 2024-03-28 16:17:57

使用split()时,将参数留空表示将删除连续的空白:

>>> line = "h3    p1   p2 p3 p4    p5"
>>> line.split()
['h3', 'p1', 'p2', 'p3', 'p4', 'p5']

从文档中:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

相关问题 更多 >