Im trying to print the first character after an element that occurs in each line.
w.txt:
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
osboxes tty7 :0 22:23 42:15 2.27s 0.23s cinnamon-session --session cinnamon
osboxes pts/1 192.168.1.17 22:25 1:26 0.06s 0.00s nano urandom.py
osboxes pts/3 192.168.1.17 22:25 1:26 0.06s 0.00s nano urandom.py
osboxes pts/0 192.168.56.117 22:25 1:26 0.06s 0.00s nano urandom.py
f = open("w.txt", "r") w = f.read()
tty = (w.split('/')[1])print(tty[0])
The above returns the id of the first pts
1
but I want it to do this for every line, and return all the integers seperated by a comma eg:
1,3,0
Ive tried the following but just returns every character in the line after 1 a bunch of times.
tty = w
for line in w:
print(tty.split('/')[1])
thanks:)
CodePudding user response:
You could use re.findall()
to scan for any digit after a /
. This will give you strings, but you can convert those to integers fairly easily.
import re
with open(path, 'r') as file:
found = re.findall(r'/(\d)', file.read())
# ['1', '3', '0']
[int(i) for i in found]
# [1, 3, 0]
CodePudding user response:
You can use list commprehension to check '/' in each character of each line then print unpacked int splitted index 0 from list with comma separator
with open("w.txt") as f:
print(*[int(line.split('/')[1][0]) for line in f.readlines() if '/' in line], sep=',')
# 1,3,0