i recently just took up python for my research studentship (so i don't have a very strong cs background). I'm dealing with a large set of image files in many different subfolders in a big folder so I want to build a python code to search and open them.
I got introduced to os and sys libraries to play around with them. I could get the file to open but that is only when I specifically put a full dirpath for the file. I'm having trouble building a code to direct python to the right folder when I only know the folder name(i'm not sure if i'm making sense haha sorry).
My goal is to be able to type the id name of a folder containing the image in the python output so the file could be pulled out and displayed.
Any suggestions would be great! thank you so much!
You should look at the documentation for the functions we recommended you in the comments. Also, you may be interested to read some tutorials on files and directory, mainly in Python.
And look at how many questions we had to ask you to understand what you wanted to do. Provide code. Explain clearly what is your input, its type, its possible values, and what is the expected output.
Anyway, from what I understood so far, here is a proposal based on os.startfile :
import os
from pathlib import Path
# here I get the path to the desired directory from user input, but it could come from elsewhere
path_to_directory = Path(input("enter the path to the folder : "))
extension_of_interest = ".jpg"
filepaths_of_interest = []
for entry in path_to_directory.iterdir():
if entry.is_file() and entry.name.endswith(extension_of_interest):
print("match: " + str(entry))
filepaths_of_interest.append(entry)
else:
print("ignored: " + str(entry))
print("now opening ...")
for filepath_of_interest in filepaths_of_interest:
os.startfile(filepath_of_interest, "open")
when run, given the path C:/PycharmProjects/stack_oveflow/animals, it prints :
enter the path to the folder : C:/PycharmProjects/stack_oveflow/animals
ignored: C:\PycharmProjects\stack_oveflow\animals\cute fish.png
match: C:\PycharmProjects\stack_oveflow\animals\cute giraffe.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute penguin.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute_bunny.jpg
now opening ...
and the 3 jpg images have been opened with my default image viewer.
The startfile function was asked to "open" the file, but there are other possibilities described in the documentation.
Related
I just want to know how can I change the name of mp4 video using python. I tried looking on the internet but could not find it. I am a beginner in python
you can use os module to rename as follows...
import os
os.rename('full_file_path_old','new_file_name_path)
So firstly let's take an example to make things clear.
Let's suppose you downloaded a playlist from YouTube which follows the following naming
C++ Tutorial Setting IDE #1.mp4 and so on...
Now when this will be saved in your computer it will be in alphabetical order and will be tough for you to watch them in proper order.
So now we know the problem let's solve it with our code and you can modify it according to your convenience.
import os
os.chdir('D:\YouTube\C++')
for f in os.listdir():
f_name, f_ext = os.path.splitext(f)
f_title, f_num = f_name.split('#')
f_title=f_title.strip()
f_num=f_num.strip()
new_name= '{}. {}{}'.format(f_num, f_title, f_ext)
os.rename(f, new_name)
Now let me explain the code to you line by line:
import os is the module we are including to use os.rename and other functions which can be found here [https://docs.python.org/3/library/os.html][1]
os.chdir is used to change your directory to the one which contains all your video files.
Then we run a for loop to go through each and every file using os.listdir which will simply list all the files in our current directory.
Now we use os.path.splitext(f)it splits our path name from its extension. So now
f_name = 'C++ Tutorial Setting IDE #1' and f_ext = .mp4
Now we will use split on our f_name as show and now what this will do is it will separate strings use # as delimiter. Now f_title = C++ Tutorial Setting IDE and f_num = 1
Now both f_title and f_num may have unwanted spaces which can be removed by using simple strip.
Now we will use some string formatting and save the final name in new_name here i have use three curly braces to format my string to look something like this 1. C++ Tutorial Setting IDE.mp4
So I hope this helps.
PS. For more info you can watch this video https://youtu.be/ve2pmm5JqmI
lately I started working with the Os module in python . And I finally arrived to this Os.path method . So here is my question . I ran this method in one of my kivy project just for testing and it actually didn't returned the correct output.The method consisted of finding if any directory exist and return a list of folders in the directory . otherwise print Invalid Path and return -1 . I passed in an existing directory and it returned -1 but the weird path is that when I run similar program out of my kivy project using the same path present in thesame folder as my python file it return the desired output .here is the image with the python file and the directory name image I have tested which returns invalid path.
and here is my code snippet
def get_imgs(self, img_path):
if not os.path.exists(img_path):
print("Invalid Path...")
return -1
else:
all_files = os.listdir(img_path)
imgs = []
for f in all_files:
if (
f.endswith(".png")
or f.endswith(".PNG")
or f.endswith(".jpg")
or f.endswith(".JPG")
or f.endswith(".jpeg")
or f.endswith(".JPEG")
):
imgs.append("/".join([img_path, f]))
return imgs
It's tough to tell without seeing the code with your function call. Whatever argument you're passing must not be a valid path. I use the os module regularly and have slowly learned a lot of useful methods. I always print out paths that I'm reading or where I'm writing before doing it in case anything unexpected happens, I can see that img_path variable, for example. Copy and paste the path in file explorer up to the directory and make sure that's all good.
Some other useful os.path methods you will find useful, based on your code:
os.join(<directory>, <file_name.ext>) is much more intuitive than imgs.append("/".join([img_path, f]))
os.getcwd() gets your working directory (which I print at the start of scripts in dev to quickly address issues before debugging). I typically use full paths to play it safe because Python pathing can cause differences/issues when running from cmd vs. PyCharm
os.path.basename(f) gives you the file, while os.path.dirname(f) gives you the directory.
It seems like a better approach to this is to use pathlib and glob. You can iterate over directories and use wild cards.
Look at these:
iterating over directories: How can I iterate over files in a given directory?
different file types: Python glob multiple filetypes
Then you don't even need to check whether os.path.exists(img_path) because this will read the files directly from your file system. There's also more wild cards in the glob library such as * for anything/any length, ? for any character, [0-9] for any number, found here: https://docs.python.org/3/library/glob.html
I am working on the listener portion of a backdoor program (for an ETHICAL hacking course) and I would like to be able to read files from any part of my linux system and not just from within the directory where my listener python script is located - however, this has not proven to be as simple as specifying a typical absolute path such as "~/Desktop/test.txt"
So far my code is able to read files and upload them to the virtual machine where my reverse backdoor script is actively running. But this is only when I read and upload files that are in the same directory as my listener script (aptly named listener.py). Code shown below.
def read_file(self, path):
with open(path, "rb") as file:
return base64.b64encode(file.read())
As I've mentioned previously, the above function only works if I try to open and read a file that is in the same directory as the script that the above code belongs to, meaning that path in the above content is a simple file name such as "picture.jpg"
I would like to be able to read a file from any part of my filesystem while maintaining the same functionality.
For example, I would love to be able to specify "~/Desktop/another_picture.jpg" as the path so that the contents of "another_picture.jpg" from my "~/Desktop" directory are base64 encoded for further processing and eventual upload.
Any and all help is much appreciated.
Edit 1:
My script where all the code is contained, "listener.py", is located in /root/PycharmProjects/virus_related/reverse_backdoor/. within this directory is a file that for simplicity's sake we can call "picture.jpg" The same file, "picture.jpg" is also located on my desktop, absolute path = "/root/Desktop/picture.jpg"
When I try read_file("picture.jpg"), there are no problems, the file is read.
When I try read_file("/root/Desktop/picture.jpg"), the file is not read and my terminal becomes stuck.
Edit 2:
I forgot to note that I am using the latest version of Kali Linux and Pycharm.
I have run "realpath picture.jpg" and it has yielded the path "/root/Desktop/picture.jpg"
Upon running read_file("/root/Desktop/picture.jpg"), I encounter the same problem where my terminal becomes stuck.
[FINAL EDIT aka Problem solved]:
Based on the answer suggesting trying to read a file like "../file", I realized that the code was fully functional because read_file("../file") worked without any flaws, indicating that my python script had no trouble locating the given path. Once the file was read, it was uploaded to the machine running my backdoor where, curiously, it uploaded the file to my target machine but in the parent directory of the script. It was then that I realized that problem lied in the handling of paths in the backdoor script rather than my listener.py
Credit is also due to the commentator who pointed out that "~" does not count as a valid path element. Once I reached the conclusion mentioned just above, I attempted read_file("~/Desktop/picture.jpg") which failed. But with a quick modification, read_file("/root/Desktop/picture.jpg") was successfully executed and the file was uploaded in the same directory as my backdoor script on my target machine once I implemented some quick-fix code.
My apologies for not being so specific; efforts to aid were certainly confounded by the unmentioned complexity of my situation and I would like to personally thank everyone who chipped in.
This was my first whole-hearted attempt to reach out to the stackoverflow community for help and I have not been disappointed. Cheers!
A solution I found is putting "../" before the filename if the path is right outside of the dictionary.
test.py (in some dictionary right inside dictionary "Desktop" (i.e. /Desktop/test):
with open("../test.txt", "r") as test:
print(test.readlines())
test.txt (in dictionary "/Desktop")
Hi!
Hello!
Result:
["Hi!", "Hello!"]
This is likely the simplest solution. I found this solution because I always use "cd ../" on the terminal.
This not only allows you to modify the current file, but all other files in the same directory as the one you are reading/writing to.
path = os.path.dirname(os.path.abspath(__file__))
dir_ = os.listdir(path)
for filename in dir_:
f = open(dir_ + '/' + filename)
content = f.read()
print filename, len(content)
try:
im = Image.open(filename)
im.show()
except IOError:
print('The following file is not an image type:', filename)
Well I searched a lot and found different ways to open program in python,
For example:-
import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.
The second one that I'm currently using
import os
os.system(fileName+'.exe')
In second example problem is:-
If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)
If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer.
and there .exe file names (like:- calculator is calc.exe you got the point).
If you want to take a look at code
Note: I want generic solution.
There's always:
from subprocess import call
call(["calc.exe"])
This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.
You can try with os.walk :
import os
exe_list=[]
for root, dirs, files in os.walk("."):
#print (dirs)
for j in dirs:
for i in files:
if i.endswith('.exe'):
#p=os.getcwd()+'/'+j+'/'+i
p=root+'/'+j+'/'+i
#print(p)
exe_list.append(p)
for i in exe_list :
print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))
ip=int(input('Enter index of file :'))
print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
exe_list stores the whole path of an exe file at each index
Can be done with winapps
First install winapps by typing:
pip install winapps
After that use the library:
# This will give you list of installed applications along with some information
import winapps
for app in winapps.list_installed():
print(app)
If you want to search for an app you can simple do:
application = 'chrome'
for app in winapps.search_installed(application):
print(app)
Hi I am currently a beginner to the python language, it is also my first language too. I need some help I am finding it difficult to know what to use to generate permanent directories sub directories and files, for eg; I want the path to generate whatever path i enter if the directories etc. don't exist, i want them created, so I enter C:\user\python\directory\sub-directory\file, then i cant workout what i should import to do the following job.
I am using Python 3.2, any advice?
You can do:
import os
os.makedirs('a/b/c', exist_ok=True)
http://docs.python.org/py3k/library/os.html
f = open("c:\file\path","w")
f.write("content of file")
First, you open the file, storing it in variable f.
You then write to it, using f.write()
Python will create the file and path if it does not exist, I think. (I am sure I've done this before, but I can't remember)
When you have finished using the file, you should use
f.close()
to close the file safely.