I'm wondering how to slice only the USERNAMES from a text file, I know the basic slicing but with the exact index only like dates and time.
The file looks like this
username: kara_v password: 123456 dept: accounting vlan: 5
username: carla_s password: 654321 dept: accounting vlan: 5
username: mary_j password: 345645 dept: accounting vlan: 5
username: leny_k password: 568890 dept: accounting vlan: 5
username: raul_t password: abscdf dept: production1 vlan: 6
username: paul_s password: hgytt dept: production1 vlan: 6
username: steph_j password: gfrrss dept: production1 vlan: 6
username: sally_g password: appookk dept: production1 vlan: 6
username: maan_h password: 123rfg dept: branch1 vlan: 11
username: ricky_m password: 678yuh dept: branch1 vlan: 11
username: zola_b password: gghh12 dept: branch1 vlan: 11
username: jeremy_n password: fgh347 dept: branch1 vlan: 11
CodePudding user response:
If you want to open the file, scan all the lines for the patter username: <some_string>
this little regex can do that:
note: usernames.txt below is the same as the lines you've posted above.
import re
with open('usernames.txt') as f:
lines = f.read()
usernames = re.findall(r'username: (.*?)[\s]', lines)
print(usernames)
re.findall
finds all occurrences of the string matchusername:
(.*?)
matches any character except a newline[\s]
escapes on any whitespace character- This prints a list of all the usernames
['kara_v', 'carla_s', 'mary_j', 'leny_k', 'raul_t', 'paul_s', 'steph_j', 'sally_g', 'maan_h', 'ricky_m', 'zola_b', 'jeremy_n']
CodePudding user response:
Would this work? considering text file name is info.txt
modified based on comment
def mysplit(x):
return x.split()[1]
with open('info.txt') as f:
lines = f.readlines()
users = list(map(mysplit,lines))
print(users)
CodePudding user response:
One more approach with sed (not thoroughly tested)
sed 's/ password.*$//;s/username: //' inputfile