我正在显示目录中当前文件的列表。
对于每个文件,我都会显示一个关联的数字,然后我想要求用户输入 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/