下面的python代码扫描txt文件并将值添加到python数组中,然后生成pdf文件。如何读取下面的txt文件并将值添加到给定的数组中?
Python代码:
from fpdf import FPDF
def createtable(spacing=1):
#data = [['Articolo / Risorsa', 'Descrizione', 'Quantita'],
# ['Mike', 'Driscoll', '3'],
# ['John', 'Doe', '2'],
# ['Nina', 'Ma', '2']
# ]
file=open("temp.txt","r")
data = [['Articolo / Risorsa', 'Descrizione', 'Quantita']]
pdf = FPDF()
pdf.set_font("Arial", size=12)
pdf.add_page()
pdf.image("logo.jpg", x=50, y=8, w=100)
pdf.ln(30)
#pdf.cell(200, 10, txt="Welcome to Python! \n \n \r ", ln=1, align="C")
col_width = pdf.w / 4.5
row_height = pdf.font_size
for row in data:
for item in row:
pdf.cell(col_width, row_height*spacing,txt=item, border=1)
pdf.ln(row_height*spacing)
pdf.output('rapportino.pdf')
if __name__ == '__main__':
createtable()
print("\n \n Rapportini in stampa \n \n ")
文件txt:
gw44;prova deec;2
gw21;ksdkoksdok;78
kosd;ldsldpsdp;21
答案 0 :(得分:2)
您可以使用此代码读取文件并填充数据
with open("file.txt", "r") as f:
lines = f.readlines()
data = [line.split("\n")[0].split(";") for line in lines]