0

I have a simple script that writes the network name to a log file. It displays the following.

All User Profile     : NET_NAME

what I would like to do is open that text file and extract just the NET_NAME part and then be able to use that as a variable and also save the text file with the changes.

I have tried using split function, it kind of works when using the text, but when trying to read from the file it doesn't work. I have searched regex but do not know the syntax to achieve what I want.

martineau
  • 119,623
  • 25
  • 170
  • 301
K.Meleo
  • 25
  • 1
  • 1
  • 8
  • is there any chance that the symbol `:` will occur somewhere else in the text other than just before `NET_NAME`? And is the space between the `:` and `NET_NAME` always there? – Tacratis Jan 16 '19 at 23:13
  • 1
    related: https://stackoverflow.com/q/1373164/2823755 – wwii Jan 16 '19 at 23:38
  • 1
    Welcome to SO. Please take the time to read [mcve], [ask] and the other links found on that page. – wwii Jan 16 '19 at 23:40
  • @ Tacratis no the log file will just have that one line in the example with one instance of : and the space after : – K.Meleo Jan 17 '19 at 07:58

1 Answers1

0

split can indeed be used to achieve this. In case you're using Python3 and the content is in text.txt file, the snippet below should be able to do the trick:

with open("text.txt", "rb") as f:
  content = f.read().decode("utf-8")
  name = content.split(":")[1].strip()

print(name)
Taras Tsugrii
  • 832
  • 6
  • 5
  • @Taras that works and extracts NET_NAME and prints the output. Is there anyway to write that to the file with out the other text? i try adding f.write(name) f.close. but i get error "line 18, in f.write(name) io.UnsupportedOperation: write" – K.Meleo Jan 17 '19 at 08:13
  • @K.Meleo, you cannot and should not write into the file that is open as read-only (`r`). You should open a file for writing `open("output.txt", "w")` and use it instead of `f`. – Taras Tsugrii Jan 18 '19 at 00:04
  • 1
    @wwii, I prefer to be explicit about the encodings I expect to find in files :) – Taras Tsugrii Jan 18 '19 at 00:04