gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:05 27 4
gpt4 key购买 nike

我是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com