2013-04-11 72 views
-4

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

+0

'os.path.mtime'将是有价值的在这里。 – squiguy 2013-04-11 08:01:38

+0

http://stackoverflow.com/questions/120656/directory-listing-in-python如何获取文件列表 – Vorsprung 2013-04-11 08:02:18

+0

@squiguy他可能想'ctime'而不是'mtime' – 2013-04-11 08:08:26

回答

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:这个问题是在初学者水平,但应该很容易通过谷歌搜索来解决。

+0

非常感谢。当我编辑你的代码如下,它正确地给了我最后创建的文件。 – user2269123 2013-04-11 08:48:20

+0

进口水珠 进口OS last_file =无 时间= 0 对于i在glob.glob( “Hello.txt_ *”): 如果os.path.getctime(I)>时间: last_file = I 时间= last_file print last_file – user2269123 2013-04-11 08:52:58

+0

@Jon Clements:非常感谢。我已经实现了我的目标有进一步增加这些线路 – user2269123 2013-04-11 09:43:08

0

从我对这个问题的理解中,你可能想忽略文件类型,因为你不能依靠它们来告诉你你想知道什么。 如果文件类型包含数字/字母数字,'sorted'将按相反顺序排序。然后你可以简单的阅读第一:

#!/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',“文件.txt_3' , 'file.txt_22', 'file.txt_21', 'file.txt_2', 'file.txt_1', 'file.txt_0'] script.py

!在/ usr/bin中/蟒蛇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))] print sorted(files,reverse = True)files = sorted(files,reverse = True)print files [0] file_to_read = open(join(directory_2_look) ,文件[0]), 'R')

打印file_to_read.read()

+0

感谢。当我检查这部分时,我得到了正在和正在打印的文件夹上创建的相同的python程序。在你给出的例子中,是否有可能只对file.txt进行这个操作,我想你应该得到file.txt_99作为输出,而不是script.py或任何其他文件。 – user2269123 2013-04-11 09:10:05

+0

是的,您只需要在另一个目录中创建脚本:-)或者,查看文件[1]。它给你第二个,因为第一个是你的脚本。但是,这很危险,比如说你在目录调用script.py1中创建另一个脚本,你需要查看文件[2]等等。最好不要在包含数据的目录中创建脚本。我只是把它放在那里,因为我希望你看到一些内容。所有其他文件都是空的! :-) – LeeO 2013-04-11 09:29:53

+0

谢谢:-)但我需要做的确切的操作,但对于只有特定名称,如“file.txt_”开始的文件,因为在我的情况下,还有其他文件与Hello.txt_一样创建像Error.txt_等。是否可能进行相同的操作,但仅限于我们感兴趣的文件? – user2269123 2013-04-11 10:03:39

相关问题