简体   繁体   English

如何允许用户使用数字输入从列表中选择文件? (即文件 x 为“1”,文件 y 为“2”等)

[英]How can I allow a user to select a file from a list using number inputs? (I.e "1" for file x, "2" for file y, etc.)

I am trying to allow the user to input a number to select a file from the displayed list.我试图让用户输入一个数字来从显示的列表中选择一个文件。

This is what the code block looks like:这是代码块的样子:

from os import listdir
from os.path import isfile, join
dates = [f for f in listdir(os.path.expanduser("~/Desktop/Sam's Calendar")) if isfile(join(os.path.expanduser("~/Desktop/Sam's Calendar"), f))]
dates = [os.path.splitext(x)[0] for x in dates]
print("The following reminders currently exist:\n")
for c, filename in enumerate(dates, 1):
    print((str(c) + "."), filename)
deletion = input ("\nPlease select the number corresponding to the reminder you want to delete.\n\n")

When I run the code, I get this result:当我运行代码时,我得到了这个结果:

The following reminders currently exist:当前存在以下提醒:

  1. 2019-05-01 2019-05-01
  2. 2019-05-02 2019-05-02

Please select the number corresponding to the reminder you want to delete.请选择您要删除的提醒对应的号码。

The results are dynamic.结果是动态的。 There is effectively no limit to the number of files within the directory.目录中的文件数量实际上没有限制。 As such, I need a solution that doesn't require me to specify the file names in the code, but one that is also dynamic.因此,我需要一种不需要我在代码中指定文件名的解决方案,但它也是动态的。

How do I go about letting the user input a number (in this case 1 or 2) to select the file for deletion?我如何让用户输入一个数字(在本例中为 1 或 2)来选择要删除的文件? I would also like to have an error if they input 0 or anything above the max (which in this case, again, is 2).如果他们输入 0 或任何高于最大值的值(在这种情况下,同样是 2),我也想有一个错误。

I managed to tinker around and figured out a way to fix this issue myself.我设法修补并找到了自己解决这个问题的方法。

This is what my result looks like:这就是我的结果:

from os import listdir
from os.path import isfile, join
dates = [f for f in listdir(os.path.expanduser("~/Desktop/Sam's Calendar")) if isfile(join(os.path.expanduser("~/Desktop/Sam's Calendar"), f))]
dates = [os.path.splitext(x)[0] for x in dates]

if len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) == 0:
    print("You currently have no reminders.")
elif len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) == 1:
    print("The following reminder currently exists:\n")
    for c, filename in enumerate(dates, 1):
        print((str(c) + "."), filename)
else:
    print("The following reminders currently exist:\n")
    for c, filename in enumerate(dates, 1):
        print((str(c) + "."), filename)

if len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) > 0:
    deletion=input("\nPlease select the number corresponding to the reminder you want to delete.\n\n")
    if deletion:
        os.remove(os.path.expanduser("~/Desktop/Sam's Calendar/" + dates[(int(deletion) - 1)] + ".txt"))

Below I will try to go through the changes I made:下面我将尝试完成我所做的更改:

1. 1.

if len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) == 0:
    print("You currently have no reminders.")

I make use of the len() function to tell the user if no files exist within the directory.我使用 len() 函数来告诉用户目录中是否不存在文件。

2. 2.

else:
    if len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) == 1:
        print("The following reminder currently exists:\n")
        for c, filename in enumerate(dates, 1):
            print((str(c) + "."), filename)

This one is redundant, really.这个是多余的,真的。 The only difference between this block and the next are the words "reminder" (instead of the plural reminders) and "exists" (instead of the plural exist)这个块和下一个块之间的唯一区别是“提醒”(而不是复数提醒)和“存在”(而不是复数存在)

If one file exists, the program outputs the name of the file in this format:如果存在一个文件,程序会以这种格式输出文件名:

  1. examplefile_a示例文件_a

3. 3.

    else:
        print("The following reminders currently exist:\n")
        for c, filename in enumerate(dates, 1):
            print((str(c) + "."), filename)

As stated, this block does the same as the previous one, but will run if 2 or more files exist in the directory.如前所述,此块与前一个块的作用相同,但如果目录中存在 2 个或更多文件,则会运行。

The output looks like this:输出如下所示:

  1. examplefile_a示例文件_a
  2. examplefile_b示例文件_b
  3. examplefile_c示例文件_c

4. 4.

    if len(os.listdir(os.path.expanduser("~/Desktop/Sam's Calendar"))) > 0:
        deletion=input("\nPlease select the number corresponding to the reminder you want to delete.\n\n")
        if deletion:
            os.remove(os.path.expanduser("~/Desktop/Sam's Calendar/" + dates[(int(deletion) - 1)] + ".txt"))

This is where the magic happens.这就是魔法发生的地方。

If there are more than 0 files, the program asks for user input.如果有 0 个以上的文件,程序会要求用户输入。 The user will input the number on the list that corresponds to the file they wish to delete.用户将在列表中输入与他们想要删除的文件对应的编号。

The Program makes "deletion" into an integer and subtracts it by 1, then uses the result to delete the correct file in the directory with this full line, where dates[0] corresponds to examplefile_a and so on:该程序将“删除”变成一个整数并减去1,然后使用该结果删除该目录中包含此完整行的正确文件,其中dates[0]对应于examplefile_a,依此类推:

os.remove(os.path.expanduser("~/Desktop/Sam's Calendar/" + dates[(int(deletion) - 1)] + ".txt"))

The reason I use subtraction is that the list in which the file names are placed starts counting from 0. This means that if the user wants to select examplefile_a (user input is "1"), due to the input, the program would select examplefile_b (the list value is "1").我使用减法的原因是放置文件名的列表从0开始计数。这意味着如果用户想要选择examplefile_a(用户输入为“1”),由于输入,程序会选择examplefile_b (列表值为“1”)。 However, the program now subtracts the user input by 1, so that when the user selects examplefile_a (user input is "1"), the program also selects examplefile_a (list value "0").但是,程序现在将用户输入减去 1,因此当用户选择 examplefile_a(用户输入为“1”)时,程序也会选择 examplefile_a(列表值“0”)。

I hope the explanation isn't too messy, and that I might help someone out in the future with the same issue.我希望解释不会太混乱,并且我可能会在将来帮助其他人解决同样的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何允许用户选择文件? - How do I allow a user to select a file? 我怎样才能 file.find("a","b","c"..... 等 "z") 和 ord("A","B","C"..... 等。蟒蛇中的“Z”) - How can I file.find("a","b","c"..... etc. "z") and ord("A","B","C"..... etc. "Z") in python 如何将python中的一个文档iedocx文件转换为python中的.Python中用户输入的目录路径? - How to convert a document i.e .docx file into .pdf in python by taking the directory path as a user input in Python? 如何允许用户使用 Json 到 Python 从 .txt 文件中删除 Object - How Can I Allow the User to Remove an Object From a .txt file Using Json through Python 如何求解函数y = f(x,y),即函数值取决于自身 - How to solve a function y=f(x,y), i.e, the functional value depends on itself 如何提示用户进行多次输入,然后将摘要打印到文件中? - How can I prompt user for multiple inputs, then print summary to a file? 如何将我的 x 和 y 坐标从文本文件添加到列表中? - How do I add my x and y coordinates into list from a text file? 如何将值列表汇总为 csv 文件中的数字 - How can I summarize the list of values into a number from csv file 如何从CSV文件中提取数据列并将其定义为x和y变量,然后使用pylab在python中绘制它们? - How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab? 如何使用Numpy在文本文件的三列中写入三个不同的值(x,y,z)? - How can I write three different values(x, y, z) in three columns a text file using Numpy?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM