Choose a file starting with a given string
PythonFilePython Problem Overview
In a directory I have a lot of files, named more or less like this:
001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...
In Python, I have to write a code that selects from the directory a file starting with a certain string. For example, if the string is 001_MN_DX
, Python selects the first file, and so on.
How can I do it?
Python Solutions
Solution 1 - Python
import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]
Solution 2 - Python
Try using os.listdir
,os.path.join
and os.path.isfile
.
In long form (with for loops),
import os
path = 'C:/'
files = []
for i in os.listdir(path):
if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i:
files.append(i)
Code, with list-comprehensions is
import os
path = 'C:/'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
'001_MN_DX' in i]
Check here for the long explanation...
Solution 3 - Python
You can use the module glob, it follows the Unix shell rules for pattern matching. See more.
from glob import glob
files = glob('*001_MN_DX*')
Solution 4 - Python
import os, re
for f in os.listdir('.'):
if re.match('001_MN_DX', f):
print f
Solution 5 - Python
You can use the os module to list the files in a directory.
Eg: Find all files in the current directory where name starts with 001_MN_DX
import os
list_of_files = os.listdir(os.getcwd()) #list of files in the current directory
for each_file in list_of_files:
if each_file.startswith('001_MN_DX'): #since its all type str you can simply use startswith
print each_file
Solution 6 - Python
with newer pathlib
module, see link:
from pathlib import Path
myDir = Path('my_directory/')
fileNames = [file.name for file in myDir.iterdir() if file.name.startswith('prefix')]
filePaths = [file for file in myDir.iterdir() if file.name.startswith('prefix')]
Solution 7 - Python
import os
for filename in os.listdir('.'):
if filename.startswith('criteria here'):
print filename #print the name of the file to make sure it is what
you really want. If it's not, review your criteria
#Do stuff with that file