Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python script that prints all word files in directory prints the documents out of order

I have a short Python script that looks in the directory I point it to and prints all of the files in it (Microsoft Word .docx format).

The entire script is below:

import os
from pathlib import Path


#set path where the files to print are
my_path = Path(__file__).parent / 'OUTPUT'
string_path = str(my_path)

#list all files in chosen folder
list_files = os.listdir(my_path)

#make the list of files into a list of paths
list_paths = [os.path.join(str(my_path), file) for file in list_files]

#this function prints everything in the folder using the paths
def print_all():
    for item in list_paths:
        os.startfile(item, "print")

#run the print function
print_all()

It works, as in it sends all the files to the default network printer and they do print, but the files are not in order when they come of the printer, although they are ordered in the directory by filename as such:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

01_firstdoc.docx
02_seconddoc.docx
03_thirddoc.docx
..etc..
20_twentiethdoc.docx

I read the following posts (post on out of order printing; another post), where one had no response, and another (first post) had some comments suggesting to add a wait time. However, I am not sure how to implement that, or if that is indeed the solution to this problem in my case. And while I understand the delay concept reasoning, I am also not sure about the race condition mentioned in the comments.

Running Windows 10 Home, and Python 3.10.5

Edit: Adding time.sleep() to the for loop has fixed the issue, as suggested below.

def print_all():
    for item in list_paths:
        os.startfile(item, "print")
        time.sleep(10)

>Solution :

To implement the delay, you just need to import time

then call time.sleep(10) (the number represents the seconds) in your code, right behind os.startfile(item, "print")

Check if it works to you. It seemed to help the person of the 2nd thread you mention.

And about the order, make sure you are actually ordering the paths and do: for item in sorted(list_paths):

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading