Python glob: how input directories and single files - python

This is an easy question.
I'm using glob to print the full hierarchy of a folder using this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import sys
import glob
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",metavar=None)
args = parser.parse_args()
def dirlist(path):
for i in glob.glob(os.path.join(path, "*")):
if os.path.isfile(i):
print (i)
elif os.path.isdir(i):
dirname = os.path.basename(i)
dirlist(i)
path = os.path.normpath(args.input)
dirlist(path)
It works pretty well, you just need to run python3 Test.py -input ..
As you can see by the argparse help description I would like to input directories but also single files.
I don't think this can be done using glob, is that right?
Can you suggest me a library that could help me print the full hierarchy of both directories and files?
I found here a long list of globe examples but they all seems to work for directories, not when you input a single file

Is nearly midnight but at least I found the solution after 2 days:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import sys
import glob
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",metavar=None)
args = parser.parse_args()
def dirlist(path):
if os.path.isfile(path):
print (path)
elif os.path.isdir(path):
for i in glob.glob(os.path.join(path, "*")):
if os.path.isfile(i):
print (i)
elif os.path.isdir(i):
dirname = os.path.basename(i)
dirlist(i)
path = os.path.normpath(args.input)
dirlist(path)

Related

Delete a specific folder with a path as a parameter in python

I want to delete a Folder named "testfolder" and all the subfolders and files in it. I want to give the "testfolder" path as a parameter when calling the python file. For example ...... (testfolder location) and there it should delete the "testfolder" when the folder exists
I guess this might be what you're looking for
import os
import shutil
pathLocation = # Whatever your path location is
if os.path.exists(pathLocation):
shutil.rmtree(pathLocation)
else:
print('the path doesn\'t exist')
You can use shutil.rmtree() for removing folders and argparse to get parameters.
import shutil
import argparse
import os
def remove_folder(folder_path='./testfolder/'):
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print(f'{folder_path} and its subfolders are removed succesfully.')
else:
print(f'There is no such folder like {folder_path}')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Python Folder Remover')
parser.add_argument('--remove', '-r', metavar='path', required=True)
args = parser.parse_args()
if args.remove:
remove_folder(args.remove)
You can save above script as 'remove.py' and call it from command prompt like:
python remove.py --remove "testfolder"
Better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function.
from shutil import rmtree
rmtree('directory-absolute-path')

Argparse: what is the difference between "sys.argv[1]" and "args.input"?

I'm learning how to use argparse and it's a labyrinth for me.
I have a code that works: if I run python Test.py . it prints all files in hierarchy using this code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import sys
import glob
#parser = argparse.ArgumentParser()
#parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None
#args = parser.parse_args()
def dirlist(path, c = 1):
for i in glob.glob(os.path.join(path, "*")):
if os.path.isfile(i):
filepath, filename = os.path.split(i)
print ('----' *c + filename)
elif os.path.isdir(i):
dirname = os.path.basename(i)
print ('----' *c + dirname)
c+=1
dirlist(i,c)
c-=1
#path = os.path.normpath(args.input)
path = os.path.normpath(sys.argv[1])
print(os.path.basename(path))
dirlist(path)
But, as I want to understand how argparse works I want to run the code using python Test.py - input .
But nothing works.
I know I'm close, I have written a sort of Frankenstein code which is commented.
Where am I wrong? I feel I'm so close to the solution...
Thank you #match for the right tips.
Problem was I was using nargs='+' in the argparse definition
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import sys
import glob
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",metavar=None)
args = parser.parse_args()
def dirlist(path, c = 1):
for i in glob.glob(os.path.join(path, "*")):
if os.path.isfile(i):
filepath, filename = os.path.split(i)
print ('----' *c + filename)
elif os.path.isdir(i):
dirname = os.path.basename(i)
print ('----' *c + dirname)
c+=1
dirlist(i,c)
c-=1
path = os.path.normpath(args.input)
print(os.path.basename(path))
dirlist(path)
The code works now!

Unable to delete files of certain extension

I'm trying to delete some archives in a folder.
Here is what I've written to do that:
import sys
import os
from os import listdir
from os.path import join
dir_path = os.path.dirname(os.path.realpath(__file__))
for file in dir_path:
if (file.endswith(".gz")) or (file.endswith(".bz2")):
os.remove(join((dir_path), file))
print("Removed file.")
print("Done.")
When I run the module, it just prints "Done." but deletes no files, even though there are files with that extension in the same directory as the module.
Can't figure out what I'm doing wrong, help?
It looks like you missed os.listdir(dir_path) in the for-loop.
This seems to have worked:
import sys
import os
from os import listdir
from os.path import join
dirdir = "/Users/kosay.jabre/Desktop/Programming/Password List"
dir_path = os.listdir(dirdir)
for file in dir_path:
if (file.endswith(".gz")) or (file.endswith(".bz2")):
os.remove(file)
print("Done.")

Using tarfile library with special characters

I want to create tarfile with Turkish characters(like "ö") but I get an error. I'm using python 2.7 on Windows 8.1.
Here is my code:
# -*- coding: utf-8 -*-
import tarfile
import os
import sys
foldername = "klasör"
foldername = foldername.decode(sys.getfilesystemencoding())
tar = tarfile.open(foldername + ".tar.gz", "w:gz", compresslevel=5)
tar.add(foldername)
tar.close()
Use "u" before the name like so.
foldername = u"klasör"
You do not need to encode/decode it, instead leave it as unicode and open like you did.

getting file path from command line argument in python

Can anyone guide me how can I get file path if we pass file from command line argument and extract file also. In case we also need to check if the file exist into particular directory
python.py /home/abhishek/test.txt
get file path and check test.txt exist into abhishek folder.
I know it may be very easy but I am bit new to pytho
import os
import sys
fn = sys.argv[1]
if os.path.exists(fn):
print os.path.basename(fn)
# file exists
Starting with python 3.4 you can use argparse together with pathlib:
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("file_path", type=Path)
p = parser.parse_args()
print(p.file_path, type(p.file_path), p.file_path.exists())
I think the most elegant way is to use the ArgumentParser This way you even get the -h option that helps the user to figure out how to pass the arguments. I have also included an optional argument (--outputDirectory).
Now you can simply execute with python3 test.py /home/test.txt --outputDirectory /home/testDir/
import argparse
import sys
import os
def create_arg_parser():
# Creates and returns the ArgumentParser object
parser = argparse.ArgumentParser(description='Description of your app.')
parser.add_argument('inputDirectory',
help='Path to the input directory.')
parser.add_argument('--outputDirectory',
help='Path to the output that contains the resumes.')
return parser
if __name__ == "__main__":
arg_parser = create_arg_parser()
parsed_args = arg_parser.parse_args(sys.argv[1:])
if os.path.exists(parsed_args.inputDirectory):
print("File exist")
Use this:
import sys
import os
path = sys.argv[1]
# Check if path exits
if os.path.exists(path):
print "File exist"
# Get filename
print "filename : " + path.split("/")[-1]

Categories

Resources