Printing text file python

can you print a file from python?

Is there some way of sending output to the printer instead of the screen in Python? Or is there a service routine that can be called from within python to print a file? Maybe there is a module I can import that allows me to do this?

There are really plenty of resources explaining that in Google — just ask for «python print to printer» and you’ll get many ideas for using lp or lpr on linux/unix/mac and/or windows modules which you could use. Proof — bytes.com/topic/python/answers/169648-print-printer and newcenturycomputers.net/projects/pythonicwindowsprinting.html

I wanted to print out a simple .txt file without any formatting requirements from a button on an interface. I was looking for a specific module name (64 bit windows machine) and function from the module.

3 Answers 3

Most platforms—including Windows—have special file objects that represent the printer, and let you print text by just writing that text to the file.

On Windows, the special file objects have names like LPT1: , LPT2: , COM1: , etc. You will need to know which one your printer is connected to (or ask the user in some way).

Читайте также:  Png html убрать фон

It’s possible that your printer is not connected to any such special file, in which case you’ll need to fire up the Control Panel and configure it properly. (For remote printers, this may even require setting up a «virtual port».)

At any rate, writing to LPT1: or COM1: is exactly the same as writing to any other file. For example:

with open('LPT1:', 'w') as lpt: lpt.write(mytext) 
lpt = open('LPT1:', 'w') print >>lpt, mytext print >>lpt, moretext close(lpt) 

If you’ve already got the text to print in a file, you can print it like this:

with open(path, 'r') as f, open('LPT1:', 'w') as lpt: while True: buf = f.read() if not buf: break lpt.write(buf) 

Or, more simply (untested, because I don’t have a Windows box here), this should work:

import shutil with open(path, 'r') as f, open('LPT1:', 'w') as lpt: shutil.copyfileobj(f, lpt) 

It’s possible that just shutil.copyfile(path, ‘LPT1:’) , but the documentation says «Special files such as character or block devices and pipes cannot be copied with this function», so I think it’s safer to use copyfileobj .

Источник

Python – Print to File

In this article, we shall look at some of the ways to use Python to print to file.

Method 1: Print To File Using Write()

We can directly write to the file using the built-in function write() that we learned in our file handling tutorial.

with open('output.txt', 'a') as f: f.write('Hi') f.write('Hello from AskPython') f.write('exit')

Output (Assume that output.txt is a newly created file)

[email protected]:~# python output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit

Method 2: Redirect sys.stdout to the file

Usually, when we use the print function, the output gets displayed to the console.

But, since the standard output stream is also a handler to a file object, we can route the standard output sys.stdout to point to the destination file instead.

The below code is taken from our previous article on stdin, stdout and stderr. This redirects the print() to the file.

import sys # Save the current stdout so that we can revert sys.stdou after we complete # our redirection stdout_fileno = sys.stdout sample_input = ['Hi', 'Hello from AskPython', 'exit'] # Redirect sys.stdout to the file sys.stdout = open('output.txt', 'w') for ip in sample_input: # Prints to the redirected stdout (Output.txt) sys.stdout.write(ip + '\n') # Prints to the actual saved stdout handler stdout_fileno.write(ip + '\n') # Close the file sys.stdout.close() # Restore sys.stdout to our old saved file handler sys.stdout = stdout_fileno

Output (Assume that output.txt is a newly created file)

[email protected]:~# python output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit

Method 3: Explicitly print to the file

We can directly specify the file to be printed in the call to print() , by mentioning the file keyword argument.

For example, the below snippet prints to the file output.txt .

print('Hi', file=open('output.txt', 'a')) print('Hello from AskPython', file=open('output.txt', 'a')) print('exit', file=open('output.txt', 'a'))

The file now has the three lines appended to it, and we have successfully printed to output.txt !

Using a context manager

However, this method isn’t the best way to resolve this situation, due to the repeated calls to open() on the same file. This wastes time, and we can do better!

The better way would be to explicitly use a context manager with statement, which takes care of automatically closing the file and using the file object directly.

with open("output.txt", "a") as f: print('Hi', file=f) print('Hello from AskPython', file=f) print('exit', file=f)

This gives the same result as before, appending the three lines to output.txt , but is now much faster, since we don’t open the same file again and again.

Method 4: Use the logging module

We can use Python’s logging module to print to the file. This is preferred over Method 2, where explicitly changing the file streams is not be the most optimal solution.

import logging # Create the file # and output every level since 'DEBUG' is used # and remove all headers in the output # using empty format='' logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='') logging.debug('Hi') logging.info('Hello from AskPython') logging.warning('exit')

This will, by default, append the three lines to output.txt . We have thus printed to the file using logging , which is one of the recommended ways of printing to a file.

References

Источник

Writing to a File with Python’s print() Function

Python’s print() function is typically used to display text either in the command-line or in the interactive interpreter, depending on how the Python program is executed. However, we can change its behavior to write text to a file instead of to the console.

In this article, we’ll examine the many ways we can write to a file with the print() function.

Redirecting a Python’s Script Output in the Terminal

The quick and dirty way to redirect a Python script’s output is directly from the command-line while executing the script.

For example, if we had a Python file called hello.py with the following contents:

print("Hallo") # Deliberately in German 

We can redirect the output of the file in the shell using a single right angle bracket:

$ python3 hello.py > output.txt 

If we open our newly created output.txt , we’ll see the following contents:

However, with this method, all output of the script is written to a file. It is often more flexible to perform this redirection from within the Python script itself.

Redirecting the Standard Output Stream

In Python, the print() function is more flexible than you might think. It was not hard-coded in such a way that specified text can only be written to the display. Instead, it sends text to a location called the standard output stream, also known as stdout .

All UNIX systems have three main pipes — standard input pipe ( stdin ), standard output pipe ( stdout ) and standard error pipe ( stderr ).

By default, the standard output pipe points to the interactive window used to execute the program, so we normally see text printed out on the screen. However, the standard output can be redirected to other locations, such as files, for convenience.

If the standard output is redirected to a specific file, the text specified in the print() function will be written to that file instead of being displayed on the screen.

In Python, a reference to the standard output can be obtained using the stdout object of the sys module. It is a file-like object, meaning it has methods that allow Python to read and write from it like an actual file.

Let’s see an example where we change stdout to be a file:

import sys print('This message will be displayed on the screen.') original_stdout = sys.stdout # Save a reference to the original standard output with open('filename.txt', 'w') as f: sys.stdout = f # Change the standard output to the file we created. print('This message will be written to a file.') sys.stdout = original_stdout # Reset the standard output to its original value 

The print() function takes the supplied string argument, appends a newline character to the end, and calls the stdout.write() method to write it to standard output.

In the example above, we first print a line of text as we’re accustomed to, which will be displayed in the console when we run the file. We then reassigned stdout to our custom file object — f . Since a file object has a perfectly valid write() method, our printed value gets written to the file without a problem.

Note that it is good practice to store the original value of the standard output in a variable before changing it. This way we can reset the standard output to its original value after we’re done, which can help avoid confusion.

Let’s save the code to a new file, printToFile.py . And then, let’s execute it:

We’ll see the following output in the Terminal:

This message will be displayed on the screen. 

And the script will create a new file called filename.txt with the following contents:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This message will be written to a file. 

You successfully redirected data from the standard output stream to a file. Let’s see how we can do this to another popular file-like object that’s dedicated to programming errors.

Redirecting the Standard Error Stream

In Python, errors are written to the standard error stream, also known as stderr . This also defaults to the interactive window but can be changed via the sys.stderr object. If we wanted to print values to the stderr , we could simply redirect the sys.stdout to point to the sys.stderr .

Create a file called printToStderr.py and add the following code:

import sys print('This message will be displayed via standard output.') original_stdout = sys.stdout # Save a reference to the original standard output sys.stdout = sys.stderr # Redirect the standard output to the standard error. print('This message will be displayed via the standard error.') sys.stdout = original_stdout # Reset the standard output to its original value 

This example is almost identical to the previous one, except that instead of redirecting the standard output stream to a file, we redirect it to the standard error stream. If the standard error stream was also redirected somewhere else, the output would be sent to that location instead of to the screen.

This message will be displayed via standard output. This message will be displayed via the standard error. 

While it may appear like regular output to us, for the computer it is displayed through different pipelines.

In the previous examples, we explicitly redirected the standard output to another file-like object by changing the stdout object. However, for convenience we can do this directly from within the print() function by specifying the output location with the file parameter:

For example, if we wanted to print directly to a file without changing the entire script’s stdout , we would write:

import sys print('This message will be displayed on the screen.') with open('filename.txt', 'w') as f: print('This message will be written to a file.', file=f) 

As we did not fiddle with redirecting the standard output explicitly, we no longer have to reset it to its initial value. As a result, this is the preferred way to write to a file with the print() function.

Note: Although the parameter’s name is file , remember that it works with any file-like object. If you wanted to print to stderr , for example, you would change the print() statement to:

print('This message will be written to stderr.', file=sys.stderr) 

Conclusion

In this article, we discussed redirecting Python’s print() function output using various methods. These methods included redirecting the output of a Python script from the command-line, redirecting the standard output within Python scripts, and specifying a file-like object in the file parameter directly in the print() function.

About the Author

This article was written by Jacob Stopak, a software developer and consultant with passion for helping others improve their lives through code. Jacob is the author of the Coding Essentials Guidebook for Developers, an introductory book that covers essential coding concepts and tools. It contains chapters on basic computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, databases/SQL, Git, and more.

Источник

Оцените статью