我是python的新手。我想根据文件名而不是数据类型读取文件。假设我在文件夹中有Hello.txt_1,Hello.txt_2,Hello.txt_3,这些文件由外部代码自动创建,Hello.txt_3是最新文件。现在,我想读取最新创建的文件Hello.txt_3并检查其内容。怎么在python中完成?我已经找到了具有通用数据类型但不能用于常见文件名的文件。
答案 0 :(得分: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:这个问题处于初级阶段,应该可以通过谷歌搜索轻松解决。
答案 1 :(得分:0)
根据我对这个问题的理解,你可能想忽略这些文件类型,因为你不能依赖它们来告诉你你想知道什么。 如果文件类型包含数字/字母数字,则“已排序”将按相反顺序对其进行排序。然后你可以简单地阅读第一个:
#!/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
来自os.path import isfile的os import listdir中的!/ usr / bin / python,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,files [0]),'r')
print file_to_read.read()