Reading Individual Lines in a .txt File as Strings

Question:

Long time lurker, first time caller. I’m using RaspberryPis and label printers to generate labels at plastic injection mold presses and need the ability to update label information via a php page hosted by Apache. I’ve written the php page to save the text fields to a .txt file and the python script to generate a label using predetermined strings, but I’m not quite understanding what I need to do to make the python program pull each line as a different string.
I need the pr, pn, cp, pd, bq, co, ma, mo, ln, and maxbox strings to be updated to corresponding lines in the text file. This seems simple, but I can’t wrap my head around it.

Here’s what the Pi prints:
example image

Here’s the python script I’m currently running. (it’s dirty, I know. I’m still learning)

from PIL import Image, ImageDraw, ImageFont #for creating label image
import RPi.GPIO as GPIO #for GPIO I/O
import os #for using CUPS print service
#from ST7920 import ST7920 #for using ST7920/128x64 monochrome LCD
import time #for LCD refresh rate
#import numpy #for forming large contiguous blocks of bytes
#from ctypes import c_void_p, c_uint8
#------------------------@section Declarations & Variables----------------------------
# 4 bit communication, backlight PWM power on GPIO18, backlight off on start
#st = ST7920(20, 5, 6, 13, 19, -1, -1, -1, -1, 16, 21, -1, 18, backlight=0, pwm=True)
count = 0 #Most recently printed box number, start at 0 so first box is 1
pr = "1" #Printer/Machine Number
pn = "FZP16WHTEPE444" #16 Digit Part Number
cp = "custpartno" #Customer Part Number
pd = "#16 Pierce Fez" #Part Description
bq = "24,000" #Quantity/box
co = "White EPE-444" #Colorant
ma = "60% HDPE M 5350/40% LDPE 1122B" #Material
mo = "2030" #MO Number
ln = "2228062030" #Lot Number
maxbox = "38" #Total Boxes

#------------------------@section Setup-----------------------------------
#st.setbacklight(1)
def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#------------------------@section Populate Label Fields-------------------
def buttonEvent(channel):
    global count
    count = count +1
    img = Image.open('/home/pi/printypi/ltemplatev2.jpg')
    d1 = ImageDraw.Draw(img)
    myFont = ImageFont.truetype('/home/pi/printypi/SANSSERIF.TTF', 60)    
    d1.text((489, 105), pn, font=myFont, fill=(0, 0, 0))
    myFont = ImageFont.truetype('/home/pi/printypi/SANSSERIF.TTF', 40)    
    d1.text((45, 250), str(pn), font=myFont, fill=(0, 0, 0))
    d1.text((380, 244), str(pd), font=myFont, fill=(0, 0, 0))
    d1.text((885, 244), str(bq), font=myFont, fill=(0, 0, 0))
    d1.text((26, 371), str(co), font=myFont, fill=(0, 0, 0))
    d1.text((379, 371), str(ma), font=myFont, fill=(0, 0, 0))
    d1.text((125, 490), str(count), font=myFont, fill=(0, 0, 0))
    d1.text((510, 490), str(mo), font=myFont, fill=(0, 0, 0))
    d1.text((798, 490), str(ln), font=myFont, fill=(0, 0, 0))
# Show label info in terminal
    print("Press #",str(pr))
    print("Part #",str(pn))
    print("Description:",str(pd))
    print("Pcs/Box:",str(bq))
    print("Color:",str(co))
    print("Material:",str(ma))
    print("MO #",str(mo))
    print("Lot #",str(ln))
    print("Box #",str(count),"of",str(maxbox))
# Save image as edited.jpg
    img.save("edited.jpg")
# Convert edited.jpg to PDF
    image1 = Image.open("edited.jpg")
    im1 = image1.convert('L')
    pdf_filename = FILE_PATH % ("pdf")        
    im1.save(pdf_filename)
# Print the resulting PDF
    os.system("lp %s" % "label.pdf")
# Do it again
def loop():
    GPIO.add_event_detect(10, GPIO.FALLING, callback = buttonEvent, bouncetime=3000)
    while True:
        pass
        
# Clear GPIO signals
def destroy():
    GPIO.cleanup()
# Listen for Kill Command
if __name__ == '__main__' :
    setup()
    try:
        loop()
    except KeyboardInterrupt: # When Ctrl + C is pressed, execute this
        destroy()

And the .php file:

Press #1

<form method="post">
        <input type="text" name="pn" placeholder="16 Digit Part #" required autocomplete="off"> <br>
        <input type="text" name="cp" placeholder="Customer Part #" required autocomplete="off"> <br>
        <input type="text" name="pd" placeholder="Part Description" required autocomplete="off"> <br>
        <input type="text" name="bq" placeholder="Quantity/Box" required autocomplete="off"> <br>
        <input type="text" name="co" placeholder="Colorant" required autocomplete="off"> <br>
        <input type="text" name="ma" placeholder="Material" required autocomplete="off"> <br>
        <input type="text" name="mo" placeholder="M.O. #" required autocomplete="off"> <br>
        <input type="text" name="ln" placeholder="Lot #" required autocomplete="off"> <br>
        <input type="text" name="mb" placeholder="Total Boxes"> <br>
        <input type="submit" name="submit" value="Submit">
</form>

<?php
if(isset($_POST['submit'])){
$pn = $_POST['pn']."
";
$cp = $_POST['cp']."
";
$pd = $_POST['pd']."
";
$bq = $_POST['bq']."
";
$co = $_POST['co']."
";
$ma = $_POST['ma']."
";
$mo = $_POST['mo']."
";
$ln = $_POST['ln']."
";
$mb = $_POST['mb']."
";
$file=fopen("newfile.txt", "w");
fwrite($file, $pn);
fwrite($file, $cp);
fwrite($file, $pd);
fwrite($file, $bq);
fwrite($file, $co);
fwrite($file, $ma);
fwrite($file, $mo);
fwrite($file, $ln);
fwrite($file, $mb);
fclose($file);
}
?>

Which saves the data to the .txt as follows:

FZP16WHTEPE444
custpartno
#16 Pierce Fez
24,000
White EPE-444       
60% HDPE M 5350/40% LDPE 1122B 
2030
2228062030    
38

For example, I need the .py to open the .txt, read line 1, and set the pn string to the value on line 1, and so on and so forth for the rest of the lines and strings/variables. I need this to happen each buttonEvent, so the script references the .txt before each label output.

Asked By: rotarybean

||

Answers:

Python has a built-in open() function to work with files (similar with what you have in your PHP file).

f = open("file.txt","r")
lines = f.readlines()

This function opens "file.txt" in read mode and output its content in the lines variable.

Using the enumerate function, you can loop through every lines and get the loop count in order to know what line you are reading.

for count, line in enumerate(lines):
    if count==1:
         # set pr value
    elif count==2:
        # set another value...

Count is the loop count automatically incremented by the enumerate function, line the value of the current line and lines the content of your .txt file.

For more informations :

How to read files in Python

Python enumerate function

In the future, if you want to add more variables to your program, I suggest using another file format like Json to store your data in order to make your code simpler. Also you could use longer variable names instead of commenting the meaning of each one, it will also make the code more readable !

Answered By: EPMR

Here is another way

key_name =[‘pr’,’pn’,’cp’,’pd’,’bq’,’co’,’ma’,’mo’,’ln’,’maxbox’]

with open(‘file.txt’) as f:
lines = [line.rstrip() for line in f]

printing = dict(zip(key_name, lines))

Answered By: fanzhefu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.