【问题标题】:How to get a file name inside a particular folder and pass that file name into a for loop index?如何在特定文件夹中获取文件名并将该文件名传递给 for 循环索引?
【发布时间】:2020-08-04 07:05:59
【问题描述】:

我有一个名为 test 的文件夹,其中包含 11.txt,12.txt,13.txt

我需要读取 test 文件夹的内容,找到最大的文本文件名并将其传递给 for 循环起始索引:

def find_largest_index(file_path):
  txt_files = glob.glob("*.*")
  #do smthing here to find the largest filename index 

file_path = 'home/Documents/PythonCodeIsHere/test'
i = find_largest_index(file_path)
for page_i in pages_num[i-1:]:
    print(page_i)

【问题讨论】:

  • 你想只读取最大文件的内容吗?
  • 我只需要文件名...在这种情况下,只需数字 13
  • 文件夹中的每个文件都命名为数字吗?我的意思是 11.txt,12.txt,13.txt...?
  • no.. 有 csv 文件,测试文件夹中有 running.txt
  • “在测试文件夹中运行 .txt”是什么意思?这个 .txt 文件与其他文件有什么区别吗?

标签: python python-3.x glob


【解决方案1】:
import os

filenames = [int(filename[:-4]) for filename in os.listdir(file_path) if ( filename.endswith('.txt') and not filename.startswith('running') )]
i = max(filenames)

【讨论】:

  • 什么是文件名[:-4] @RandomGuy
  • 只是删除字符串的'.txt'部分,只保留数字('11','12',...)。由于它仍然是一个字符串,因此您需要将其转换为 int,因此 int(filename[:-4])
猜你喜欢
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
相关资源
最近更新 更多