Skip to main content
 首页 » 编程设计

python之从 0 开始计算列表

2025年05月04日7webabcd

到目前为止,这是我的代码,它是一个基于文本的文件浏览器。用户通过选择分配的编号来选择要浏览的驱动器或目录。当您运行脚本时,它会显示从 0 到任意数量的项目的输出。但是当显示文件夹的内容时,它会从 1 开始列出,这会打乱您的选择。

from os import listdir 
import win32api 

#need help with this block 
def glist(path): 
    global nlist 
    nlist = [] 
    for i in listdir(path): 
        nlist.append(i) 
        countf=len(nlist) 
        print str(countf) + " " + str(i) 

def getfiles(dir, filename): 
    for i in listdir(dir): 
        newtext=open(filename,'a') 
        newtext.write("\n"+ "\n" + i) 
        newtext.close() 
 
def getdrives(): 
    global drives 
    drives = win32api.GetLogicalDriveStrings() 
    drives = drives.split('\000')[:-1] 
    for index, item in enumerate(drives): 
 
      print index, item 
 
 
print "Select which drive to work with: " 
getdrives() 
 
x = raw_input("Which Drive:") 
glist(drives[int(x)]) 
 
y = raw_input("Select Folder: ") 
glist(drives[int(x)] + nlist[int(y)]) 

请您参考如下方法:

最好写成:

def glist(path): 
    global nlist 
    for idx, name in enumerate(listdir(path)): 
        print '{} {}'.format(idx, name)  
    nlist.append(name) 

但会重新考虑使用 global 并从中返回一个列表...