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

标签 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

最佳答案

您应该避免使用 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(',')]

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

关于Python:根据用户输入打印一个或多个文件(副本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677132/

相关文章:

python - 从 Eclipse 运行 django 服务器时没有这样的表错误

javascript - Django - simplejson 响应

python - 机器人框架 - UnicodeDecodeError : 'ascii' codec can't decode byte 0xe9 in position 49: ordinal not in range(128) while inputting text

python - 用户路径中的 utf-8 字符阻止模块被导入

python - 卸载用户在 macOS High Sierra 上使用 pip 安装的所有软件包

Python字符串切片,如果包含字符串结尾的特殊情况?

python - 删除从文件读取的列表中的换行符

python - FiPy 不工作

python - 使用 zipfile.ZipFile 即时打开 urllib2.urlopen() 的响应

python - 在 MAC OSX 上使用 PY2APP 打包 key 环模块时出错