ricardo.santos
Posts: 38
Joined: Thu Jan 18, 2018 12:18 pm

open txt file and get variables inside

Thu Mar 15, 2018 9:36 pm

hi. i'm newbie in python and need some help

I have a txt file like with a structure like that below

Code: Select all

####inputs
###bla-bla-bla

xpto = 2
zzz = 10.25
name = Jonh
###

interval = 2
....

#####
How can I do in python to open the file, and get the variables as strings that have the equal sign (=)

User avatar
DougieLawson
Posts: 34167
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: open txt file and get variables inside

Thu Mar 15, 2018 11:38 pm

Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

ricardo.santos
Posts: 38
Joined: Thu Jan 18, 2018 12:18 pm

Re: open txt file and get variables inside

Fri Mar 16, 2018 9:20 am

will this work on the pi
I don't have the lib in the python3 by default
is that not specifically for ini files in windows
thanks

User avatar
DougieLawson
Posts: 34167
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: open txt file and get variables inside

Fri Mar 16, 2018 9:29 am

Python is python regardless. Things only won't work if they have a hardware dependency like a GPIO pin driver.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4248
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: open txt file and get variables inside

Fri Mar 16, 2018 10:52 am

I assume you've checked the standard library and there's nothing there to help.
In that case I'd
pull in the file with readlines
filter out any text after the first #
remove leading whitespace
filter out blank lines
use a regular expression such as "^([^=]+)=([^=]+)$" to split each line in two.

That probably could be reduced to almost that number of lines of code by using filter and map.

gordon77
Posts: 3430
Joined: Sun Aug 05, 2012 3:12 pm

Re: open txt file and get variables inside

Fri Mar 16, 2018 2:42 pm

This was an interesting question and I feel I've learnt something. :D

I assumed you want to read the lines and set the read variables with the values read. Maybe l went further than you asked?

Maybe not the most efficient but works with your data in data.txt

Code: Select all

with open("data.txt", "r") as file:
   inputx = file.readlines()

for lines in range (0,len(inputx)):
   a = (inputx[lines])
   b =  a.split("=",2)
   if len(b) == 2:
      c = str.strip(b[0])
      d = str.strip(b[1])
      e = d.replace('.','',1)
      if str.isdecimal(d):
         f = int(b[1])
      elif str.isdecimal(e):
         f = float(b[1])
      else:
         f = b[1]
      globals()[c] = f


# check variables read and set

print (xpto,zzz,name,interval)

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4248
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: open txt file and get variables inside

Sat Mar 17, 2018 12:30 am

Yeah, split is better than a regular expression.
It can be done more neatly with maps, filters and comprehensions though.

Code: Select all

with open("variables.txt","r") as f: stuff = f.readlines()

#remove everything after first # and split at first =
stuff = map(lambda x: x[:x.find("#")].split("=",1), stuff)
#remove blank lines and lines without an =
stuff = filter(lambda x: len(x) > 1, stuff)
#strip leading and trailing whitespace
stuff = map(lambda x: [y.strip() for y in x], stuff)
#convert to dictionary
variables = {d[0]:d[1] for d in stuff}

print (variables)
print ("name is ", variables["name"])
This produces:

Code: Select all

{'xpto': '2', 'zzz': '10.25', 'name': 'Jonh', 'nothingafterequal': '', 'interval': '2'}
name is Jonh
I also delayed doing the strip until I could get at the spaces around the = as well.

Return to “Python”