wngrtzk
Posts: 5
Joined: Sun Jan 26, 2020 9:52 pm

Print (from printer) random line from .txt file

Sat Apr 18, 2020 11:10 am

Hi,

I have a .txt file with around 10.000 lines.
I need help writing a script that prints (as in print from a USB printer via CUPS) one of these sentences randomly each time I run the script.

As you probably can tell, I am new to programming with python.

What would a script like this look like?

Thanks!

hippy
Posts: 7908
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Print (from printer) random line from .txt file

Sat Apr 18, 2020 6:01 pm

This is one way to get a random line from a file and print it to the terminal command line. You will need to change the file name and figure out how to print the line to a printer -

Code: Select all

import random

def GetRandomLineFromFile(filename):
  with open(filename,"r") as f:
    lines = f.read().split("\n")
  return lines[random.randint(0, len(lines)-1)]

line = GetRandomLineFromFile("file.txt")
print(line)

Return to “Python”