python - 使用与每个文件关联的编号而不是文件名上传文件

标签 python

我正在显示目录中当前文件的列表。

对于每个文件,我都会显示一个关联的数字,然后我想要求用户输入 3 个文件,但不是文件名,我想使用关联的数字。

所以我将每个文件名与字典中关联的数字存储起来。

现在我尝试使用与每个文件关联的编号上传,但我没有成功。

有人已经做过类似的事情并且可以给我帮助吗?

import os 

def upload(file_name_number): 

    filename = raw_input(file_name_number)

    if(os.path.exists(filename)):
        key.set_contents_from_filename(filename)
    else:
        print "The selected number does not exist in current directory."
        upload(file_name_number)
    return filename    

def create():

    showListAndSaveDict()

    firstFile  = upload("Select the number of first file:")
    secondFile = upload("Select the number of second file:")
    thirdFile  = upload("Select the number of third file:") 

def showListAndSaveDict():
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    files_dict = {}
    i=0
    for f in files:
        i = i+1
        print (str(i) + " - " + f)  
        files_dict[i] = f
    return files_dict

create()

最佳答案

您正在创建一个字典来将数字映射到文件名,但在上传功能中您正在检查带有数字的文件是否存在,这将是错误的,因为文件存储的是名称而不是数字。您需要检查该数字是否存在字典中是否存在。

import os

def upload(file_name_number,files_dict): 

    filename = int(raw_input(file_name_number))
    #as the key to dictionary is integer
    if filename in files_dict:
        # upload code here
        print "dummy"
    else:
        print "The selected number does not exist in current directory."
        upload(file_name_number,files_dict)#why are you calling this again
    return filename

def create():
    files_dict = showListAndSaveDict()
    firstFile  = upload("Select the number of first file:",files_dict)
    secondFile = upload("Select the number of second file:",files_dict)
    thirdFile  = upload("Select the number of third file:",files_dict)

def showListAndSaveDict():
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    files_dict = {}
    i=0
    for f in files:
        i = i+1
        print (str(i) + " - " + f)  
        files_dict[i] = f
    return files_dict

create()

关于python - 使用与每个文件关联的编号而不是文件名上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29397725/

相关文章:

python - 从这种类型的图像中读取文字是否可行?如果是这样,我将如何做呢?

python - Django 管理站点丢失了所有格式

python - django-taggit 自定义 'tag' 模型和 request.user

python - 如何将具有特定文件扩展名的文件复制到我的 python(2.5 版)脚本中的文件夹中?

python - Airflow 在同一个 dag 的不同时间运行任务?

Python 和 Json : Multiline input data into Json

python - 你如何确保在失败的子任务中调用 Celery chord 回调?

python - 在numpy数组中没有for循环的迭代

python - 如何使用字符串格式使用 "{0.word}"

python - Octave 测试模块