简体   繁体   English

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

[英]Reading Individual Lines in a .txt File as Strings

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.我正在使用 RaspberryPis 和标签打印机在塑料注塑模具印刷机上生成标签,并且需要能够通过 Apache 托管的 php 页面更新标签信息。 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.我已经编写了 php 页面以将文本字段保存到 .txt 文件和 python 脚本以使用预定字符串生成标签,但我不太了解我需要做什么才能使 python 程序将每一拉为不同的字符串。 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.我需要将 pr、pn、cp、pd、bq、co、ma、mo、ln 和 maxbox 字符串更新为文本文件中的相应行。 This seems simple, but I can't wrap my head around it.这看起来很简单,但我无法理解它。

Here's what the Pi prints: example image这是 Pi 打印的内容:示例图片

Here's the python script I'm currently running.这是我目前正在运行的 python 脚本。 (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:和 .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);
}
?>

Which saves the data to the .txt as follows:它将数据保存到 .txt 中,如下所示:

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.例如,我需要 .py 打开 .txt,读取第 1 行,并将 pn 字符串设置为第 1 行的值,以此类推,以此类推其余行和字符串/变量。 I need this to happen each buttonEvent, so the script references the .txt before each label output.我需要在每个 buttonEvent 中发生这种情况,因此脚本在每个标签输出之前引用 .txt。

Python has a built-in open() function to work with files (similar with what you have in your PHP file). Python 有一个内置的 open() 函数来处理文件(与 PHP 文件中的类似)。

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

This function opens "file.txt" in read mode and output its content in the lines variable.此函数以读取模式打开“file.txt”并将其内容输出到变量中。

Using the enumerate function, you can loop through every lines and get the loop count in order to know what line you are reading.使用enumerate函数,您可以遍历每一行并获取循环计数,以便知道您正在阅读哪一行。

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. Count 是由 enumerate 函数自动递增的循环计数,将当前行的值排成一行,并将 .txt 文件的内容排成一行。

For more informations :欲了解更多信息:

How to read files in Python如何在 Python 中读取文件

Python enumerate function Python枚举函数

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.将来,如果您想在程序中添加更多变量,我建议使用另一种文件格式,例如 Json 来存储您的数据,以使您的代码更简单。 Also you could use longer variable names instead of commenting the meaning of each one, it will also make the code more readable !您也可以使用更长的变量名而不是注释每个变量的含义,这也会使代码更具可读性!

Here is another way这是另一种方式

key_name =['pr','pn','cp','pd','bq','co','ma','mo','ln','maxbox'] 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] with open('file.txt') as f:lines = [line.rstrip() for line in f]

printing = dict(zip(key_name, lines))打印 = dict(zip(key_name, lines))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM