{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## ``Q6.`` ## \n", "\n", "## ```Perform the following file operations using Python```## \n", "\n", "## ```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.``` \n", "\n", "## ```b) Read a file contents and copy only the contents at odd lines into a new file.``` ##" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## -----------------------------------------------------------------------------------------------------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Approach to displaying the files and subdirectories in each level** \n", "\n", "1. Get path information from the user.

\n", "\n", "2. Check whether the path exists or not.

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

\n", "\n", "4. Normalize the paths and count the number of subdirectories and files in each of those subdirectories.

\n", "\n", "5. Display the names of subdirectories and files in subdirectories (including root directory).

\n", "\n", "\n", "**Below functions are used in the program**\n", "\n", "`os.path.exists(path)` \n", "\n", "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. \n", "\n", "`os.path.normpath(path)` \n", " \n", "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. \n", "\n", "`os.walk(topdir[, topdown=True])` \n", "\n", "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`). \n", " \n", "1. `dirpath` is a string, the path to the directory.

\n", "\n", "2. `dirnames` is a list of the names of the subdirectories in dirpath (excluding '.' and '..').

\n", "\n", "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).

\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## -----------------------------------------------------------------------------------------------------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Approach to copy the contents from one file to another file at odd lines** \n", "\n", "1. Open a file source_file as in_file in read mode.

\n", "\n", "2. Open a file destination_file as out_file in write mode.

\n", "\n", "3. To read all the lines of a file use `f.readlines().`

\n", "\n", "4. Obtain the total number of lines in the file.

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

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ------------------------------------------------------------------------------------------------------------------------" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your choice\n", "Press 1 --> Display files and directories for a given path and their count\n", "Press 2 --> Copy the contents present at odd lines to another file\n", "Press 3 --> Exit the program\n", "1\n", "Enter path to traverse: \n", "C:\\Test_Data\n", "Found directory: C:\\Test_Data \n", "\n", "File name(s) 1.txt \n", "\n", "Found directory: C:\\Test_Data\\Root_Dir \n", "\n", "File name(s) 2.txt \n", "\n", "Found directory: C:\\Test_Data\\Root_Dir\\Sub_Dir_1 \n", "\n", "File name(s) 3.txt \n", "\n", "Found directory: C:\\Test_Data\\Root_Dir\\Sub_Dir_1\\Sub_Dir_2 \n", "\n", "File name(s) 4.txt \n", "\n", "File name(s) 5.txt \n", "\n", "Number of subdirectories are 3 \n", "\n", "Number of files are 5 \n", "\n", "Enter your choice\n", "Press 1 --> Display files and directories for a given path and their count\n", "Press 2 --> Copy the contents present at odd lines to another file\n", "Press 3 --> Exit the program\n", "2\n", "Enter the Source file name: source_file.txt\n", "\n", "\n", "Enter the Destination file name: destination_file.txt\n", "\n", "\n", "File contents at odd lines copied to destination file \n", "\n", "Enter your choice\n", "Press 1 --> Display files and directories for a given path and their count\n", "Press 2 --> Copy the contents present at odd lines to another file\n", "Press 3 --> Exit the program\n", "3\n" ] } ], "source": [ "import os\n", "\n", "\n", "def display_files():\n", " # Set the directory to start from\n", " print(\"Enter path to traverse: \")\n", " root_dir = input()\n", " if os.path.exists(root_dir):\n", " dir_count = 0\n", " file_count = 0\n", " for dir_name, sub_dir_list, file_list in os.walk(root_dir):\n", " print(f\"Found directory: {dir_name} \\n\")\n", " # check to ignore starting directory while taking directory count\n", " # normpath returns the normalized path eliminating double slashes etc.\n", " if os.path.normpath(root_dir) != os.path.normpath(dir_name):\n", " dir_count += 1\n", " for each_file_name in file_list:\n", " file_count += 1\n", " print(f\"File name(s) {each_file_name} \\n\")\n", " print(f\"Number of subdirectories are {dir_count} \\n\")\n", " print(f\"Number of files are {file_count} \\n\")\n", " display_menu()\n", " else:\n", " print(\"Entered path doesn't exist\")\n", " display_menu()\n", "\n", "\n", "def copy_contents_to_file():\n", " source_file = input(\"Enter the Source file name: \")\n", " print(\"\\n\")\n", " destination_file = input(\"Enter the Destination file name: \")\n", " print(\"\\n\")\n", " try:\n", " with open(source_file) as in_file, open(destination_file, \"w\") as out_file:\n", " list_of_lines = in_file.readlines()\n", " for i in range(0, len(list_of_lines)):\n", " if i % 2 != 0:\n", " out_file.write(list_of_lines[i])\n", " except IOError:\n", " print(\"Error in file names\")\n", "\n", " print(\"File contents at odd lines copied to destination file \\n\")\n", " display_menu()\n", "\n", "\n", "def display_menu():\n", " print(\"Enter your choice\")\n", " print(\"Press 1 --> Display files and directories for a given path and their count\")\n", " print(\"Press 2 --> Copy the contents present at odd lines to another file\")\n", " print(\"Press 3 --> Exit the program\")\n", " choice = int(input())\n", "\n", " if choice == 1:\n", " display_files()\n", " elif choice == 2:\n", " copy_contents_to_file()\n", " else:\n", " exit()\n", "\n", "\n", "if __name__ == \"__main__\":\n", " display_menu()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 1 }