首页 > 解决方案 > 如何在 Python 中返回整个字符串并从中提取一列?

问题描述

例如,从这个输出中,我需要带有单词“test1.txt”的字符串,然后我需要这个字符串的第三列,即文件大小。Linux中的“cut”命令之类的东西

5636335  -rw-        1922  Apr 20 2019 09:22:47 +00:00  private-config.cfg
5636332  -rw-        1136  Apr 20 2019 09:22:47 +00:00  NETMAP
5636336  -rw-        0     Apr 20 2019 13:14:51 +00:00  test1.txt
5636325  -rw-        1691  Apr 20 2019 09:22:47 +00:00  startup-config.cfg
5636333  -rw-       16384  Apr 20 2019 09:22:47 +00:00  nvram_00001
5636330  -rw-         341  Apr 20 2019 09:22:47 +00:00  ubridge.log

NETMIKO module
net_connect = ConnectHandler(**cisco)
output = net_connect.send_command('dir')
x = re.search('test1.txt', output)
print(x)

<re.Match object; span=(215, 224), match='test1.txt'>

标签: pythonregex

解决方案


您可以使用:

tr -s ' ' <test1.txt | cut -d ' ' -f3

1922
1136
0
1691
16384
341

ts -s | squeeze-repeats
cut -d | delimiter
cut -f | field

我知道如何在 Linux 中做到这一点,我需要 Python 帮助

import re
sizes = [re.split(r"\s+", l)[2] for l in open("test1.txt").readlines()]
# ['1922', '1136', '0', '1691', '16384', '341']

推荐阅读