如果在目录中存在的话,如何在Python3中打印txt文件?

时间:2017-06-06 22:27:48

标签: python-3.x printing

我有这样的事情:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""

import os
import sys
import subprocess
#import win32print

if sys.platform == "linux" or sys.platform == "linux2":
    # linux
    lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
    lpr.stdin.write("This is a print-test sentence")
elif sys.platform == "darwin":
    # MAC OS X
    pass
elif sys.platform == "win32":
    # Windows
    os.startfile("C:/temp/temp.txt", "print")

我想知道如何在Linux中打印文件temp.txt,就像在Win示例中一样,如果文件存在于脚本目录中,如何打印*.txt文件一)是和如何改变该文件的编码(我需要DOS 852代码页)?

1 个答案:

答案 0 :(得分:1)

要检查任何系统上的文件是否存在,我认为仍然是最好的内置方法os.path.isfile( filepath )。如果上面的代码适用于linux和windows,你可以这样做:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""
import os
import sys
import subprocess
#import win32print

filepath = 'some_file_path'
if os.path.isfile(filepath):
    if sys.platform == "linux" or sys.platform == "linux2":
        # linux
        lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
        with open(filepath,'r') as file:
            lpr.stdin.write(file.read())

    elif sys.platform == "darwin":
        # MAC OS X
        pass
    elif sys.platform == "win32":
        # Windows
        os.startfile(filepath, "print")