-4

私はpythonが初めてです。データ型ではなくファイル名に基づいてファイルを読み取りたい。フォルダーに Hello.txt_1、Hello.txt_2、Hello.txt_3 があり、これらのファイルが外部コードによって自動的に作成され、Hello.txt_3 が最新のファイルであるとします。ここで、作成された最新のファイル Hello.txt_3 を読み取り、その内容を確認します。どのようにpythonで行われますか? 一般的なデータ型のファイルを見つけましたが、一般的なファイル名は知りませんでした。

4

2 に答える 2

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

!/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)) ] 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()

于 2013-04-11T08:52:34.053 に答える