Python:在用户输入上打印一个或多个文件(副本)

时间:2016-09-24 13:55:55

标签: python python-2.7

我是Python的新手。 我正在尝试创建一个程序来打印我经常每周手工打印的文档集,但是我遇到了几个问题:

以下是代码:

import os

file_list = os.listdir("C:/Python27/Programs/PrintNgo/Files2print")
print ("List of available documents to print" '\n')

enum_list = ('\n'.join('{}: {}'.format(*k) for k in enumerate(file_list)))
print(enum_list)

user_choice = input('\n' "Documents # you want to print: ")
copies = input("How many copies would you like from each: ")
#not implemented
current_choice = file_list[user_choice]
current_file = os.startfile("C:/Python27/Programs/PrintNgo/Files2print/"+current_choice, "print")

这是输出:

List of available documents to print

0: doc0.docx
1: doc1.docx
2: doc2.docx
3: doc3.docx
4: doc4.docx
5: doc5.docx

Documents # you want to print: 

我设法从0-5输入数字并打印所需的文件,但输入2个值如下:2,3不工作并抛出错误。如何一次打印多个?

如果我想制作每个文档的副本。让我们说我选择2,3应该循环重复每个动作多次,因为我想要副本数量?

I wonder if my style is fine, however that kind of menu looks nice as well and I can try it eventually

1 个答案:

答案 0 :(得分:1)

您应该避免使用Python 2中的input函数。它可能很方便,但存在安全风险。相反,您应该使用raw_input函数。在Python 3中,名为input的函数等同于Python 2的raw_input,旧的Python 2 input函数的功能已被删除。

下面的代码显示了如何处理以逗号分隔的列表中给出的多个文档编号。该代码还处理单个文档编号。如果用户提供任何非整数值,程序将以ValueError崩溃。但是,输入中允许使用空格。

from __future__ import print_function

user_choice = raw_input("\nDocuments # you want to print: ")
user_choice = [int(u) for u in user_choice.split(',')]
copies = int(raw_input("How many copies would you like from each: "))

for i in range(copies):
    print('Copy', i + 1)
    for j in user_choice:
        print('Printing document #', j)

<强>演示

Documents # you want to print: 3, 2,7
How many copies would you like from each: 2
Copy 1
Printing document # 3
Printing document # 2
Printing document # 7
Copy 2
Printing document # 3
Printing document # 2
Printing document # 7

此代码的核心是str.split方法。

user_choice.split(',')

获取user_choice中的字符串并将其拆分为字符串列表,在找到逗号的任何地方拆分,丢弃逗号。

[int(u) for u in user_choice.split(',')]

获取每个结果字符串并将它们转换为整数,将结果存储在列表中。