2

Ok don't yell at me. I'm still learning.

Text file (file.txt, these are the entire contents):

pn = FZP16WHTEPE444
cp = custpart
pd = partdesc
bq = 11,000
co = color 02
ma = material 01
mo = 1234
ln = 2227011234
mb = 38

Python code:

print(str(pn))
print(str(cp))
print(str(pd))
print(str(bq))
print(str(co))
print(str(ma))
print(str(mo))
print(str(ln))
print(str(mb))

What do I do to make the python script call the strings from the text file so it'll display the following?:

FZP16WHTEPE444
custpart
partdesc
11,000
color 02
material 01
1234
2227011234
38
rotarybean
  • 39
  • 4
  • Rather than a bunch of variables, you probably want a [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). (Also, `print` automatically converts things to strings if necessary. And look into `for` loops for repetitive tasks like this.) – CrazyChucky Jul 22 '22 at 18:05
  • Usually I yell at people who tell me not to yell at them, but since you didn't use any !s, I won't this time. ;-) – Fiddling Bits Jul 22 '22 at 18:10

3 Answers3

1

You can read content from file and split base = and store in dict and use dict for printing values.

dct = {}
with open('file.txt', 'r') as file:
    for line in file:
        k, v = line.split('=')
        dct[k.strip()] = v.strip()
        
keys = ['pn' , 'cp' , 'pd', 'bq', 'co', 'ma', 'mo', 'ln', 'mb']
for k in keys:
    print(dct[k])

FZP16WHTEPE444
custpart
partdesc
11,000
color 02
material 01
1234
2227011234
38
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
0

You can read the text file then create a dictionary with the values:

with open("file.txt", "r") as f:
    f = f.read()
    f = f.split("\n")
    vals = dict(map(lambda val : val.split(" = "), f))
print(vals["pn"])
print(vals["cp"])
linger1109
  • 500
  • 2
  • 11
0

Here is one way:

test.txt

pn = FZP16WHTEPE444
cp = custpart
pd = partdesc
bq = 11,000
co = color 02
ma = material 01
mo = 1234
ln = 2227011234
mb = 38

test.py

with open("test.txt") as file:
    dictionary = {}
    for line in file:
        entry = [x.strip() for x in line.split("=")]
        dictionary[entry[0]] = entry[1]
print("{}".format(dictionary), flush=True)
$ python test.py
{'pn': 'FZP16WHTEPE444', 'cp': 'custpart', 'pd': 'partdesc', 'bq': '11,000', 'co': 'color 02', 'ma': 'material 01', 'mo': '1234', 'ln': '2227011234', 'mb': '38'}
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
  • 1
    It's good practice to [use `open` as a context manager](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files), using the `with` keyword, rather than manually closing the file yourself. – CrazyChucky Jul 22 '22 at 18:11
  • @CrazyChucky Thanks for the tip. I wasn't aware this was a context manager. – Fiddling Bits Jul 22 '22 at 18:14