2017-06-12 12 views
0

我有一個文件夾,其中包含我將用python解析的幾個日誌文件。Python從列表中選擇一個文件

我將顯示包含到像一個文件夾中的文件列表:

  • [1] FileName1.log
  • [2] FileName2.log

,然後用戶可以選擇正確的文件寫入文件列表號碼。

例如,解析文件「FileName2.log」用戶請按2

在我的劇本我可以顯示文件的列表,但我現在不如何從列表中選擇一個文件按指數。

這是我的腳本

import os 
import sys 

items = os.listdir("D:/Logs") 

fileList = [] 

for names in items: 
    if names.endswith(".log"): 
     fileList.append(names) 

cnt = 0 
for fileName in fileList: 
    sys.stdout.write("[%d] %s\n\r" %(cnt, fileName)) 
    cnt = cnt + 1 


fileName = raw_input("\n\rSelect log file [0 -" + str(cnt) + " ]: ") 

感謝您的幫助!

+0

的Python的版本是您使用解決您的目的是什麼? – inspectorG4dget

+0

提示:使用枚舉有一個更pythonic和可讀的代碼'cnt,fileName枚舉(fileList):' –

回答

1

如果你有這樣的一個數組的名字:

fileList = ['FileName1.log','FileName2.log'] 

你可以通過使用他們的索引(記住,這些數字是0索引)將它們拉出來,所以當你要求用戶輸入一個數字(例如0,1,2)時,你將使用該數字來代替fileList[0]將是'FileName1.log' 獲取你想要的文件。像這樣:

fileToRead=fileList[userInput] 

,如果你問你1,2,3需要使用userInput-1,以確保它是正確的0索引。 那就請你打開你現在有一個文件:從0

f=open(fileToRead, 'r') 

您可以在許多其他語言閱讀更多關於蟒蛇開放here

+0

謝謝!我解決了我的問題。我認爲從索引中選擇一個列表元素是不可能的。我認爲這隻可能在元組上。 – Federico

1

如果fileList是文件列表,並fileName是用戶輸入,你可以參考用戶選擇使用下列文件:

fileList[fileName] 
+0

由於日誌文件名非常長,我會避免用戶對文件的全名進行數字。我將選擇帶有文件列表索引的文件。 – Federico

+0

是的,這正是這個代碼正在做的。用戶只需鍵入索引。 –

+0

感謝您的建議 – Federico

0

只需添加到底這樣的事情...

sys.stdout.write(fileList[int(fileName)]) 
0

索引作爲開始試試這個:

import os 
import sys 

items = os.listdir("D:/Logs") 

fileList = [] 

for names in items: 
    if names.endswith(".log"): 
     fileList.append(names) 

cnt = 0 
for fileName in fileList: 
    sys.stdout.write("[%d] %s\n\r" %(cnt, fileName)) 
    cnt = cnt + 1 


fileName = int(raw_input("\n\rSelect log file [0 - " + str(cnt - 1) + "]: ")) 
print(fileList[fileName]) 

您需要將來自raw_input()的輸入轉換爲int。然後你可以使用獲得的數字作爲你的列表的索引。 0是第一個文件,1是第二個文件等

0
import glob 
import os 

dirpath = r"D:\Logs" # the directory that contains the log files 
prefix = "FileName" 
fpaths = glob.glob(os.path.join(dirpath, "{}*.log".format(prefix))) # get all the log files 
fpaths.sort(key=lambda fname: int(fname.split('.',1)[0][len(prefix):])) # sort the log files by number 

print("Select a file to view:") 
for i,fpath in enumerate(fpaths, 1): 
    print("[{}]: {}".format(i, os.path.basename(fpath))) 

choice = int(input("Enter a selection number: ")) # assuming valid inputs 
choice -= 1 # correcting for python's 0-indexing 

print("You have chosen", os.path.basename(fpaths[choice])) 
1
import os 
import sys 

items = os.listdir("D:/Logs") 

fileList = [name for name in items if name.endswith(".log")] 

for cnt, fileName in enumerate(fileList, 1): 
    sys.stdout.write("[%d] %s\n\r" % (cnt, fileName)) 

choice = int(input("Select log file[1-%s]: " % cnt)) 
print(fileList[choice]) 

你自己的代碼稍加修改的版本,希望這

相關問題