我从终端中的命令生成数据netstat -a
,现在结果是我写入文件的所有传入和传出 IP 地址,如何通过列仅检索 IP 地址?
另外,如何按列参数检索数据?例如,从第 10 列开始,到第 27 列结束。我尝试了过滤器功能,但它不起作用。谢谢!
我从终端中的命令生成数据netstat -a
,现在结果是我写入文件的所有传入和传出 IP 地址,如何通过列仅检索 IP 地址?
另外,如何按列参数检索数据?例如,从第 10 列开始,到第 27 列结束。我尝试了过滤器功能,但它不起作用。谢谢!
这个怎么样:
with open('data.txt') as inf:
for lc, line in enumerate(inf, 1): # lc - current line count
if lc > 3: # if you need to skip some header lines ?? (unknown data)
cols = line.split()
for i in xrange(10, 28): # print column 10 - 27
print cols[i], ' ',
print
如果您可以发布一些带有问题的数据,那将会很有帮助,因此我使用您的示例列10 - 27来代替。
filename = ...
with open(filename, 'rb') as f:
for row in f.readlines()[1:]:
columns = row.split()
if len(columns) > 2:
print row.split()[1]
这与 Levon 的答案基本相同,但稍微更紧凑和 Pythonic,并且调整了数字以猜测我怀疑 OP 试图做什么。
with open('data.txt') as inf:
for lc, line in enumerate(inf): # lc - current line count
if lc >= 2: # netstat usually has 2 lines of header info
print ' '.join(line.split()[3:5]) # cols 3-4 are the addresses