gpt4 book ai didi

Python 从列表中选择一个文件

转载 作者:行者123 更新时间:2023-11-30 22:35:37 24 4
gpt4 key购买 nike

我有一个文件夹,其中包含几个我将用 python 解析的日志文件。

我会显示文件夹中包含的文件列表,例如:

  • [1] 文件名1.log
  • [2] 文件名2.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) + " ]: ")

感谢您的帮助!

最佳答案

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])

您拥有经过少量修改的代码版本,希望这能解决您的目的

关于Python 从列表中选择一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com