Read a text file, iterate over a list#
Read a text file#
# Open a text file in reading mode ('r'):
with open('data/for_loop_haiku.txt', 'r') as f:
# f is a variable and holds the file object
# Read the text file into a new variable called txt:
txt = f.read()
# Now the data is available:
print(txt)
Iterate and count,
Loop through tasks with steady play,
End when done repeating.
from fpdf import FPDF
pdf = FPDF(format=(115, 180))
with open('data/for_loop_haiku.txt', 'r') as f:
txt = f.read()
pdf.add_page()
pdf.set_font('helvetica', size=24)
pdf.set_y(40)
pdf.multi_cell(w=0, h=10, text=txt, align='L')
pdf.output("pdfs/haiku.pdf")
Encoding#
When the text includes special characters like German Umlauts, then it’s sometimes necessary to specifiy the encoding of the text (commonly utf-8).
# Reading without encoding
with open('data/for_loop_haiku_german.txt', 'r', encoding='utf8') as f:
txt = f.read()
print(txt)
Schleifen durch das Feld,
Zählend kreisen, bis's vollbracht,
Fortschritt Schritt für Schritt.
Read text as a list#
Now we’ll use written words as page numbers.
First we’ll get a list of written words and store them in the file wordlist.txt
inside the folder data
.
from fpdf import FPDF
pdf = FPDF(format=(115, 180))
pdf.set_font('Helvetica')
# Read the content of a textfile into the variable wordlist
with open('data/wordlist.txt', 'r') as f:
wordlist = f.readlines()
# Iterate over all items of the list called wordlist
for word in wordlist:
pdf.add_page()
pdf.set_y(-24)
pdf.set_font_size(10)
# for each iteration, the next item of the list is
# stored in the variable called word
pdf.cell(w=0, text=word, align='R')
pdf.output("pdfs/wordlist.pdf")