-1

I have a text file with data

Theme="dark_background"
Color="Blue"

Now from the text file I just want to read the value of a Theme in python i.e dark_background

    with open("nxc.txt","r") as f:
        asz = f.read()

Above is the code for reading whole text file

Mohit Narwani
  • 169
  • 2
  • 11
  • 1
    You need to do it line by line. `for line in f:` / `parts = f.split('='`)` / `if parts[0] =="Theme":` etc. – Tim Roberts Dec 12 '22 at 23:01
  • Also check out the [`readline`](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects) function. – Bill Dec 12 '22 at 23:05

3 Answers3

4

Don't call .read() (which slurps the whole file when you only need one line), just loop over the file object itself (which is an iterator of its lines) until you find the line you care about:

with open("nxc.txt") as f:
    for line in f:
        name, sep, value = line.rstrip().partition('=')  # Remove trailing whitespace, split on = at most once
        if sep and name == 'Theme':  # Cheap to confirm it split by check if sep non-empty, then check if found correct name
            break  # You found it, break out of the loop
# value contains whatever is to the right of the equals after Theme
print(value)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Something like this,

Theme=""
Color=""

with open('c:\\config.file') as f:
    for line in f:
        if line.startswith("Theme"):
            Theme = line.split("=")[1].strip()
        if line.startswith("Color"):
            Color = line.split("=")[1].strip()
Madison Courto
  • 1,231
  • 13
  • 25
-1

If you just want to read the first line of a file, you can use readline() eg.

    with open("nxc.txt","r") as f:
        asz = f.readline()

If you want to read a particular value, you have no choice but to load the whole file and parse it in Python. This is because Python has no idea about the overall structure of the file.