Q6.

Perform the following file operations using Python

a) Traverse a path and display all the files and subdirectories in each level till the deepest level for a given path. Also, display the total number of files and subdirectories.

b) Read a file contents and copy only the contents at odd lines into a new file.

-----------------------------------------------------------------------------------------------------------------------------

Approach to displaying the files and subdirectories in each level

  1. Get path information from the user.

  2. Check whether the path exists or not.

  3. If the path exists, then walk through all the file and subdirectories (including root directory) using os.walk() function.

  4. Normalize the paths and count the number of subdirectories and files in each of those subdirectories.

  5. Display the names of subdirectories and files in subdirectories (including root directory).

Below functions are used in the program

os.path.exists(path)

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to access the requested file, even if the path physically exists.

os.path.normpath(path)

Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. On Windows, it converts forward slashes to backward slashes.

os.walk(topdir[, topdown=True])

Generate the file names in a directory tree by walking the tree either top-down (default) or bottom-up (topdown = False). Specifying argument topdown is optional. For each directory in the tree rooted at directory topdir (including topdir itself), it yields a 3-tuple (dirpath, dirnames, filenames).

  1. dirpath is a string, the path to the directory.

  2. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..').

  3. filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

-----------------------------------------------------------------------------------------------------------------------------

Approach to copy the contents from one file to another file at odd lines

  1. Open a file source_file as in_file in read mode.

  2. Open a file destination_file as out_file in write mode.

  3. To read all the lines of a file use f.readlines().

  4. Obtain the total number of lines in the file.

  5. Check the line number which is not divisible by 2 and then write the contents to out_file else pass.

------------------------------------------------------------------------------------------------------------------------

In [1]:
import os


def display_files():
    # Set the directory to start from
    print("Enter path to traverse: ")
    root_dir = input()
    if os.path.exists(root_dir):
        dir_count = 0
        file_count = 0
        for dir_name, sub_dir_list, file_list in os.walk(root_dir):
            print(f"Found directory: {dir_name} \n")
            # check to ignore starting directory while taking directory count
            # normpath returns the normalized path eliminating double slashes etc.
            if os.path.normpath(root_dir) != os.path.normpath(dir_name):
                dir_count += 1
            for each_file_name in file_list:
                file_count += 1
                print(f"File name(s) {each_file_name} \n")
        print(f"Number of subdirectories are {dir_count} \n")
        print(f"Number of files are {file_count} \n")
        display_menu()
    else:
        print("Entered path doesn't exist")
        display_menu()


def copy_contents_to_file():
    source_file = input("Enter the Source file name: ")
    print("\n")
    destination_file = input("Enter the Destination file name: ")
    print("\n")
    try:
        with open(source_file) as in_file, open(destination_file, "w") as out_file:
            list_of_lines = in_file.readlines()
            for i in range(0, len(list_of_lines)):
                if i % 2 != 0:
                    out_file.write(list_of_lines[i])
    except IOError:
        print("Error in file names")

    print("File contents at odd lines copied to destination file \n")
    display_menu()


def display_menu():
    print("Enter your choice")
    print("Press 1 --> Display files and directories for a given path and their count")
    print("Press 2 --> Copy the contents present at odd lines to another file")
    print("Press 3 --> Exit the program")
    choice = int(input())

    if choice == 1:
        display_files()
    elif choice == 2:
        copy_contents_to_file()
    else:
        exit()


if __name__ == "__main__":
    display_menu()
Enter your choice
Press 1 --> Display files and directories for a given path and their count
Press 2 --> Copy the contents present at odd lines to another file
Press 3 --> Exit the program
1
Enter path to traverse: 
C:\Test_Data
Found directory: C:\Test_Data 

File name(s) 1.txt 

Found directory: C:\Test_Data\Root_Dir 

File name(s) 2.txt 

Found directory: C:\Test_Data\Root_Dir\Sub_Dir_1 

File name(s) 3.txt 

Found directory: C:\Test_Data\Root_Dir\Sub_Dir_1\Sub_Dir_2 

File name(s) 4.txt 

File name(s) 5.txt 

Number of subdirectories are 3 

Number of files are 5 

Enter your choice
Press 1 --> Display files and directories for a given path and their count
Press 2 --> Copy the contents present at odd lines to another file
Press 3 --> Exit the program
2
Enter the Source file name: source_file.txt


Enter the Destination file name: destination_file.txt


File contents at odd lines copied to destination file 

Enter your choice
Press 1 --> Display files and directories for a given path and their count
Press 2 --> Copy the contents present at odd lines to another file
Press 3 --> Exit the program
3