Python CLI to copy contents of all the files in the current directory



First, we explore what "os.walk()" returns. We have following directory structure:

C:\Users\Ashish Jain\OneDrive\Desktop\test>tree /f

C:.
│   3.txt
│
├───1
│   └───a
│           b.txt
│
└───2
        a.txt 

Then we find how "os.walk()" works on it:
C:\Users\Ashish Jain\OneDrive\Desktop\test>python 
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32

>>> for dirpath, subdirs, files in os.walk("."):
...  for f in files:
...   print(f)
...   print(dirpath)
...   print(subdirs)
...
3.txt
.
['1', '2']
b.txt
.\1\a
[]
a.txt
.\2
[]
>>> 

Here is the Python code snippet run in Python CLI to copy contents of all the files in the current directory and subdirectories:
>>> for dirpath, subdirs, files in os.walk("."):
...  for f in files:
...   os.system("echo Filename: " + os.path.join(dirpath, f) + " >> abc.txt")
...   os.system('type "' + os.path.join(dirpath, f) + '" >> abc.txt') 

No comments:

Post a Comment