【问题标题】:Select file in a directory by index/number按索引/编号选择目录中的文件
【发布时间】:2020-08-07 05:43:50
【问题描述】:

我需要从列表中读取文件。具体来说,我需要查找存储在特定目录中的文件。由于它可能不记得存储在那里的所有文件或只是正确的名称,我需要列出他们的。为了完成这一步,我发现了这篇有用的帖子:

How do I display the the index of a list element in Python?

现在我有一个如下列表:

file=[]

for f in glob.glob("*.txt"):
    file.append(f)


for (num,item) in enumerate(file):
    print(num+1,item)        # updated after Thierry's comment

输出:

1 file 1.txt
2 file_2.txt
3 file_3.txt
...

我想使用

读取文件
query=input("Please add your selection: ") # just the number
if int(query) in enumerate(datasets):
    dataset=pd.read_csv('path_name'+1) # I would need to add the path to the file and, by the number, the filename 
df = pd.DataFrame(dataset)

它给了我错误:TypeError: 'module' object is not iterable.

我该怎么做?

【问题讨论】:

  • 您使用的答案的开头确实是个糟糕的建议。不要那样使用index。使用enumerate查看答案的结尾或其他答案。

标签: python pandas


【解决方案1】:

就像 Thierry 在 cmets 中所说的那样,我可能会避免使用这种方法并尝试这样的方法:

files = [f for f in glob.glob("*.txt")]

for fi, f in enumerate(files):
    print(fi, f)

query = input("Please add your selection: ") # just the number
df = pd.read_csv(files[int(query)])

【讨论】:

  • 不要对副作用使用列表推导:[print()... for...] 无用地创建了一个 Nones 列表(打印函数的返回值)。当目标是创建一个列表时使用理解,否则编写正常循环。参见例如stackoverflow.com/questions/5753597/…
【解决方案2】:

您也可以尝试使用字典稍有不同的方法。

import os
import pandas as pd

# iterate over a list of files in directory
filelist = [files for files in os.listdir("<path to directory>")]

# convert the files list to a dictionary
filelist_dict = { ind: name for (ind,name) in enumerate(filelist) }

# ask for user input
userinput = int(input("Enter a number :"))

# open the file based on the key input by user
with open(filelist_dict[userinput]) as file:
       df = pd.read_csv(file)  # read the csv file into a pandas dataframe
       print(df)               # print the dataframe

希望这会有所帮助:)

【讨论】:

  • 选择查询后,如何返回正文?例如,如果我选择 4 并且我想查看其对应的文本,那么在您展示给我的步骤中是否也可以?如果您愿意,我可以提出一个新问题
  • @still_learning 如果你想打开一个文件并读取它的内容,那么在片段的最后一部分,而不是 file.read();你可以像 pandas.read_csv("filename") 这样读取 csv 文件。我已经更新了代码。检查这是否有帮助
  • 首先非常感谢您回答我。我试过你的代码,但我认为我做错了什么,因为它给了我一个错误。但是,主要问题是我看不到文件列表,而只写了要选择的数字。我想了解是否有可能,在选择数字后,尝试取回文件名,以便仅使用“文件”(如 stackoverflow.txt 而不是 1)创建一个新文件。我打开一个新问题:stackoverflow.com/questions/61415508/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多