Python Files and Directories Operation

In this article, I have implemented the following two functions.

  1. Read all files from a folder.
  2. Read the specific files from a folder.

Read all files from a folder

Show you the code directly.

import os
import sys

global fileNameList

def showAllFileName(filePath):

    fileNames = os.listdir(filePath)
    for fileName in fileNames:
        addPrefixFileName = filePath + '/' + fileName
        #print(addPrefixFileName)
        if os.path.isdir(addPrefixFileName):           
            showAllFileName(addPrefixFileName)
        else:
            print(fileName)

if __name__ == '__main__':
    if len(sys.argv) < 2 :
        print("Please enter a directory\n")
        exit()

    checkFolder = os.path.isdir(sys.argv[1])
    if not checkFolder:
        print("Please enter a directory\n")
        exit()
    filePath = (sys.argv)[1]
    showAllFileName(filePath)

The following is my test folder structure.

After run “python main.py folder1” command, the following shows the result.

Read the specific files from a folder

First, show you the code.

import os
import sys

global fileNameList

def showAllFileName(filePath):

    fileNames = os.listdir(filePath)
    for fileName in fileNames:
        addPrefixFileName = filePath + '/' + fileName
        #print(addPrefixFileName)
        if os.path.isdir(addPrefixFileName):           
            showAllFileName(addPrefixFileName)
        else:
            if fileName.endswith('.vm'):
                print(fileName)

if __name__ == '__main__':
    if len(sys.argv) < 2 :
        print("Please enter a directory\n")
        exit()

    checkFolder = os.path.isdir(sys.argv[1])
    if not checkFolder:
        print("Please enter a directory\n")
        exit()
    filePath = (sys.argv)[1]
    showAllFileName(filePath)

Then, The following is the folder structure.

After run “python main.py folder1” command, the following shows the result.

The following are some Python Usage Examples. You can access it to get more details.

How to Use Global Variable in Python

Have a good day, take care!

Share this article to your social media
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments