Question: I am very new to python. I want to read files based on file name and not data type. Say I have Hello.txt\_1, Hello.txt\_2, Hello.txt\_3 in a folder and these files are created automatically by an external code with Hello.txt\_3 being the latest file. Now, I want to read the latest created file Hello.txt\_3 and check for its contents. How is to be done in python ? I have figured out for files with common data type but not for common file name.

Answer: 
Use glob to perform wildcard matching. The following example will find all the files named as you state and `last_file` will contain the name of the latest by creation time (or `None` if no files were found).

```
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: This question is at the very beginner level however and should have been easily solved by googling.
From my understanding of the question, you probably want to ignore the file types as you cannot depend on them to tell you what you want to know.
If the file type contains a number/alpha-numeric, 'sorted' will sort it in reverse order. Then you can simple read the first:

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

```

Results will look a bit like this:

> 
> ['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()
> 
> 
>