Python get files in directory by mask

How To List Files With A Certain Extension in Python

before going to list a files with certain extension, first list all files in the directory then we can go for the required extension file. In python to list all files in a directory we use os.listdir library. In this we have to mention the path of a directory which you want to list the files in that directory. For this we have to import os.

import os x = os.listdir(r"C:\Users\enaknar\Desktop\pycharm") print (x) for i in x: print(i)

Output:

[ '1-1.py', '1-2.py', '1-3.py', 'asf', 'asf.txt', 'fsg.py', 'read-1.py'] 1-1.py 1-2.py 1-3.py asf asf.txt fsg.py read-1.py

Here we are storing all the files of a directory “C:\Users\enaknar\Desktop\pycharm” in variable x as a list.

we are printing the list x and we are printing list one by one using for loop. in this way we can print or list all files in a particular directory.

List Files With A Certain Extension in Python

in the previous example we have seen how to list all files in a directory, now in this example i will show you how to print or list the files with certain extension.

#find a file ends with .txt import os x = os.listdir(r"C:\Users\devops\Desktop\pycharm") for i in x: if i.endswith(".txt"): print(i)

to check a file with certain extension in python we use endswith method. The endswith() method returns True if a string ends with the specified suffix. If not, it returns False.

asf.txt Process finished with exit code 0

so here writing one more if loop like if it is finds a file with extension with “.txt” it will print the file.

Читайте также:  Google sheets and java

in this way we can print or list f iles with a certain extension in python.

  • List Files With A Certain Extension in Python
  • list all files in a directory in python
  • python list files in a directory
  • list files in a directory python

Источник

How to Find all files in a Directory with specific extension in Python

How to Find all files in a Directory with specific extension in Python

Python comes with a standard module called os that is used to handle file management using Python. With the help of Python os modules, we can perform many file management tasks like creating, renaming, moving, copying, searching, and deleting files and directories. If you want to know more about Python file management with the os module then click here .

In this tutorial, we will not be covering all the important methods of the os module. Instead, we will be using it to find specific extension files from a directory. For example, we will be writing a python script that can find all the .txt, .doc, .py, .jgeg, etc., files from a specific directory.

Python program to find all the .txt files from a directory

We will start with finding all the .txt files present in a specific directory. For this tutorial, I will be searching all the .txt files present in the same directory where my Python script is located and printing the complete path as an output.

import os for file in os.listdir(): if file.endswith(".txt"): print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Desktop\code\data.txt C:\Users\tsmehra\Desktop\code\external_css.txt C:\Users\tsmehra\Desktop\code\external_script.txt C:\Users\tsmehra\Desktop\code\passwords_list.txt C:\Users\tsmehra\Desktop\code\vulnarable_banners.txt

The os.listdir() function will return a list of all the files and directories present in the current directory. The .endswith() is a Python string function that will check if a file ends with an extension of .txt . The os.getcwd() function returns the absolute path of the current working directory. The os.path.join() method will join the current working directory path with the file name. In the above example, I have listed all the .txt files that are present in the same directory where the Python script is located. If you want to find files of different directories there you need to change the working directory by using the os.chdir() method.

import os directory = r'C:\Users\tsmehra\Documents' os.chdir(directory) #change the current working directory for file in os.listdir(): if file.endswith(".txt"): print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Documents\allnew.txt C:\Users\tsmehra\Documents\config.txt C:\Users\tsmehra\Documents\Python has many built.txt

It’s very important to use the r»» prefix before the directory name else we need to specify the escape characters.

Python program to find all the Python .py files from a directory

The program will remain the same. The only change we need to make in order to retrieve all the .py files is in the endswith() method.

import os #directory = r'' #os.chdir(directory) #change the current working directory for file in os.listdir(): if file.endswith(".py"): #only python .py files print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Desktop\code\assambaly.py C:\Users\tsmehra\Desktop\code\attack.py C:\Users\tsmehra\Desktop\code\checkweather.py C:\Users\tsmehra\Desktop\code\client.py C:\Users\tsmehra\Desktop\code\colorful.py C:\Users\tsmehra\Desktop\code\compareimage.py C:\Users\tsmehra\Desktop\code\contours.py C:\Users\tsmehra\Desktop\code\crackpassword.py C:\Users\tsmehra\Desktop\code\CssJSlinks.py C:\Users\tsmehra\Desktop\code\dDosattqack.py C:\Users\tsmehra\Desktop\code\deconde.py C:\Users\tsmehra\Desktop\code\DecryptFile.py . 

Python program to find all the Images .jpeg, .jpg, .png files from a directory

Now let’s find all the images present in a specific directory. The code will remain pretty the same as we have written for the above examples, but here will be making some changes in the conditional if statement.

import os directory = r'C:\Users\tsmehra\Pictures' os.chdir(directory) #change the current working directory to pictures for file in os.listdir(): if file.split(".")[-1].lower() in ["apng", "avif", "gif","jpeg", "jpg", "png", "svg"]: print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Pictures\Armstrong_Number_Python.jpg C:\Users\tsmehra\Pictures\Arrays-data-structure.png C:\Users\tsmehra\Pictures\arrays.png C:\Users\tsmehra\Pictures\atom.png C:\Users\tsmehra\Pictures\best python libraries 2021.jpg C:\Users\tsmehra\Pictures\blur faces with open cv.jpg C:\Users\tsmehra\Pictures\choosepython.jpg C:\Users\tsmehra\Pictures\contours image opencv python.jpg C:\Users\tsmehra\Pictures\contours on the blank image.jpg C:\Users\tsmehra\Pictures\coolpad python online copiler.jpg

Conclusion

Let’s sum up the above Python tutorial. In this tutorial, you learned how to find specific file extensions in Python. The module we used in our tutorial is os which is a Python standard module for file and directory management. If you are searching for the files that are present in the same directory of your Python script, then you do not need to change the working directory, but if you wish to find files from another directory there, you need to change the working directory using the os.chdir() method. The os.listdir() will list out all the directories and files present in the current working directory, and using the if statement and endswith() statement we can find the specific extension files.

People are also reading:

Источник

Поиск файла по маске (ключевым словам)

День добрый!
Как можно реализовать в Питоне поиск файла по маске, когда у нас есть, например начало название файла и расширение файла, а то что между ними — неважно. Думал с помощью glob и join, а оно мне ошибку бьёт!

Пример кода:
Имя искомого файла, например SFLU.2021-05-11_11-12-13.pdf

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import datetime, os, shutil, glob, fnmatch currdir = os.path.dirname(__file__) cur_date = datetime.datetime.now() day = cur_date.day month = cur_date.month year = cur_date.year hour = cur_date.hour minute = cur_date.minute d = '2>'.format(day) mon = '2>'.format(month) h = '2>'.format(hour) minn = '2>'.format(minute) mask = currdir + '\\SFLU.' + str(year) + '-' + mon + '-' + d files = glob.glob(os.path.join(mask, "*.pdf")) print(files)

В бат-скриптах есть замечательный символ *, который очень просто в обращении, где * поставил, там и не учитывается. Есть ли альтернатива в Питоне? Команды Виндовс в коде использовать не хочу.

Источник

Оцените статью