top of page
  • Black Facebook Icon
  • Black Instagram Icon
  • Black Twitter Icon
  • Black Pinterest Icon

Simple file search using python for beginners

  • Writer: Admin
    Admin
  • Jun 18, 2020
  • 1 min read

There may be many instances when you want to search a system.Suppose while writing an application you may want to have all the ‘.mp4’ files present. Well here’s how to do it in a simple way.

This code searches all the files and print their name. If you want some other kinds of files just change the extension.


import os
file_type = '.mp4'

location = os.lisdir('desktop')
for file in location:
    if file.endswith(file_type):
        print(file)

EXPLANATION :


line 1 :


Import the OS module, It provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules.


line 2 :


Assign the type of file ( '.mp4', '.mp3' etc ) to the variable "file_type".


line 3 :


Assign the path of the directory where your files are saved to the variable "location". This can be done with the help of "listdir() ". Python method listdir() returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.


line 4 :


Create a for loop.


line 5 :


In this we check whether the file ends with the extension '.mp4' or not. If it is true then file name will print otherwise the loop checks for another file. This code comes under for loop that's why it is in an indented block.


line 6 :


The name of the file print when print code executes and prints the name of all the available files.



Try changing the file extension or path in the code and see what happens.








Comments


bottom of page