Harikrishnan V Nair Harikrishnan V Nair -3 years ago 84
Python Question

Extracting value from a key value pair in a .txt file using python

I have a text file containing a single line containing a key and a value.
Eg:
Name: xyz

From python how can I import that text file and fetch the name ie., xyz

Answer Source
open('filename.txt').readline().split(':')[1].strip()
  • open('filename.txt') opens the file
  • .read reads the line
  • .split(':')[1] splits the line on : and takes the second element (the value)
  • .strip() strips the value from the first space
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download