簡體   English   中英

將 .txt 文件中的單行讀取為字符串

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

長期潛伏,第一次來電。 我正在使用 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()

此函數以讀取模式打開“file.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','cp','pd','bq','co','ma','mo','ln','maxbox']

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM