【问题标题】:Reading files based on file name and not data type根据文件名而不是数据类型读取文件
【发布时间】:2013-04-11 07:58:51
【问题描述】:

我对 python 很陌生。我想根据文件名而不是数据类型读取文件。假设我在一个文件夹中有 Hello.txt_1、Hello.txt_2、Hello.txt_3,这些文件是由外部代码自动创建的,Hello.txt_3 是最新文件。现在,我想阅读最新创建的文件 Hello.txt_3 并检查其内容。如何在 python 中完成?我已经找出了具有通用数据类型的文件,但没有找到通用文件名。

【问题讨论】:

标签: python file names


【解决方案1】:

使用 glob 执行通配符匹配。以下示例将查找您指定的所有文件,last_file 将包含按创建时间命名的最新文件的名称(如果未找到文件,则为 None)。

import glob
import os

last_file = None
time=0
for i in glob.glob("Hello.txt_*"):
    if os.path.getctime(i) > time: 
        last_file = i

PS:不过,这个问题还处于初级水平,应该很容易通过谷歌搜索解决。

【讨论】:

  • 非常感谢。当我如下编辑您的代码时,它正确地给了我最后创建的文件。
  • import glob import os last_file = None time=0 for i in glob.glob("Hello.txt_*"): if os.path.getctime(i) > time: last_file = i time= last_file 打印 last_file
  • @Jon Clements:非常感谢。通过进一步添加这些行,我已经实现了我的目标
  • @Jon Clements: import glob import os last_file = None time=0 for i in glob.glob("Hello.txt_*"): if os.path.getctime(i) > time: last_file = i time= last_file print last_file f = open(last_file, 'r') q= f.read() print q
【解决方案2】:

根据我对问题的理解,您可能希望忽略文件类型,因为您不能依赖它们来告诉您您想知道的内容。 如果文件类型包含数字/字母数字,“排序”将按相反顺序对其进行排序。然后你可以简单的阅读第一个:

#!/usr/bin/python
from os import listdir
from os.path import isfile, join

#this is where you declare you directory
directory_2_look = '/var/tmp/lee/'

#This creates a list of the contents of your directory
files = [ f for f in listdir(directory_2_look) if isfile(join(directory_2_look,f)) ]

#this sorts the files for you in reverse order
files = sorted(files, reverse=True)
print files[0]

#this allows you to read the last file and print it out. If you want to write to it simply change the 'r'
file_to_read = open(join(directory_2_look,files[0]), 'r')

print file_to_read.read()

结果看起来有点像这样:

['script.py', 'file.txt_99', 'file.txt_4', 'file.txt_3', 'file.txt_22', 'file.txt_21', 'file.txt_2', 'file.txt_1', 'file.txt_0'] script.py

!/usr/bin/python from os import listdir from os.path import isfile, join directory_2_look = '/var/tmp/lee/' files = [ f for f in

listdir(directory_2_look) if isfile(join(directory_2_look,f)) ] 打印 排序(文件,反向=真)文件=排序(文件,反向=真)打印 files[0] file_to_read = open(join(directory_2_look,files[0]), 'r')

打印file_to_read.read()

【讨论】:

  • 非常感谢。当我检查这部分时,我得到了在正在打印的文件夹上创建的相同 python 程序。在您给出的示例中,是否可以仅对 file.txt 进行此操作,我猜您应该将 file.txt_99 作为输出而不是 script.py 或任何其他文件。
  • 是的,您只需要在另一个目录中创建脚本 :-) 或者,查看文件 [1]。它为您提供第二个,因为第一个是您的脚本。但是,这很危险,假设您在目录调用 script.py1 中创建了另一个脚本,您将需要查看文件 [2] 等等。最好不要在包含您的数据的目录中创建脚本。我只是把它放在那里,因为我想让你看到一些内容。所有其他文件都是空的! :-)
  • 谢谢 :-) 但是我需要执行确切的操作,但是对于仅以特定名称开头的文件,例如“file.txt_”,因为在我的情况下,还有其他文件与 Hello.txt_ 一起创建,例如Error.txt_ 等。是否可以进行相同的操作,但只针对我们感兴趣的文件?
猜你喜欢
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2021-03-13
  • 2018-10-16
相关资源
最近更新 更多