将.txt文件中的单行作为字符串读取



长期潜伏者,第一次调用。我使用RaspberryPis和标签打印机在塑料注塑机上生成标签,并需要通过Apache托管的php页面更新标签信息的能力。我已经编写了php页面来将文本字段保存到.txt文件,并编写了python脚本来使用预定的字符串生成标签,但我不太明白我需要做什么才能使python程序将每个拉成不同的字符串。我需要将pr、pn、cp、pd、bq、co、ma、mo、ln和maxbox字符串更新到文本文件中的相应行。这看起来很简单,但我无法理解

以下是Pi打印的内容:示例图像

这是我目前正在运行的python脚本。(我知道它很脏。我还在学习(

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()

php文件:

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);
}
?>

它将数据保存到.txt中,如下所示:

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

例如,我需要.py来打开.txt,读取第1行,并将pn字符串设置为第1行的值,依此类推,用于其余行和字符串/变量。我需要在每个buttonEvent发生这种情况,所以脚本在每个标签输出之前引用.txt。

Python有一个内置的open((函数来处理文件(与PHP文件中的类似(。

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

该功能打开";文件.txt";在读取模式下,并在变量中输出其内容。

使用enumerate函数,您可以循环遍历每一行并获取循环计数,以便知道您正在读取哪一行。

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

Count是由enumerate函数自动递增的循环计数,行为当前行的值,行为.txt文件的内容。

有关更多信息:

如何在Python 中读取文件

Python枚举函数

将来,如果您想在程序中添加更多变量,我建议使用另一种文件格式,如Json来存储数据,以使代码更简单。此外,您可以使用更长的变量名,而不是注释每个变量的含义,这也会使代码更可读!

这里有另一种方法

key_name=['pr','pn','p','pd','q','c','ma','mo','n','maxbox']

open('file.txt'(为f:lines=[line.rstrip((用于f]中的行

printing=dict(zip(key_name,lines((

最新更新