Iterate a directory for all files with file extension '.py' - python

I am attempting to find every file in a directory that contains the file extension: '.py'
I tried doing:
if str(file.contains('.py')):
pass
I also thought of doing a for loop and going through each character in the filename but thought better of it, thinking that it would be too intense, and concluded that there would be an easier way to do things.
Below is an example of what I would want my code to look like, obviously replacing line 4 with an appropriate answer.
def find_py_in_dir():
for file in os.listdir():
#This next line is me guessing at some method
if str(file.contains('.py')):
pass

Ideally, you'd use endswith('.py') for actual file extensions, not checking substrings (which you'd do using in statements)
But, forget the if statement
https://docs.python.org/3/library/glob.html
import glob
for pyile in glob.glob('*.py'):
print(pyile)

if requires a boolean and not a string, so remove the str and replace .contains with .__contains__
if file.__contains__ ('.py'):
You can also do:
if '.py' in file:

Related

Python add prefix to file names inside a directory

I need to add a prefix to file names within a directory. Whenever I try to do it though, it tries to add the prefix to the beginning of the file path. That won't work. I have a few hundred files that I need to change, and I've been stuck on this for a while. Have any ideas? Here's the closest I've come to getting it to work. I found this idea in this thread: How to add prefix to the files while unzipping in Python? If I could make this work inside my for loop to download and extract the files that would be cool, but it's okay if this happens outside of that loop.
import os
import glob
import pathlib
for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
dst = f"County_{file}"
os.rename(file, os.path.join(file, dst))
That produces this error:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg' -> 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg\\County_C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg'
I'd like to add "County_" to each file. The targeted files use this syntax: CountyName_WaterWells.ext
os.path.basename gets the file name, os.path.dirname gets directory names. Note that these may break if your slashes are in a weird direction. Putting them in your code, it would work like this
import os
import glob
import pathlib
for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
dst = f"County_{os.path.basename(file)}"
os.rename(file, os.path.join(os.path.dirname(file), dst))
The problem is your renaming variable, dst, adds 'County_' before the entire path, which is given by the file variable.
If you take file and break it up with something like file.split("/") (where you should replace the slash with whatever appears between directories when you print file to terminal) then you should be able to get file broken up as a list, where the final element will be the current filename. Modify just this in the loop, put the whole thing pack together using "".join(_path + modified_dst) and then pass this to os.rename.

Need convert function output to string from use as an arguement Python

Creating Hazel rule that triggers a script when a .mp4 file is dropped in.
Here is the script:
import os
from os import path
from vimeo import VimeoClient
a = "/Path/to/MyVimeoDirectory"
def myfile():
for file in os.listdir("/Path/to/MyVimeoDirectory"):
if file.endswith(".mp4"):
return os.path.join(a, file)
vimeo = VimeoClient("blahblahvimeotoken")
vimeo.upload(myfile)
So basically vimeo.upload() requires a string argument. I've done a ton of research and saw some examples but I can't get them to work for me here. How do I get the resulting path of myfile() to put quotes around the output so I can use it as a string? Thoughts?
In your final line, consider that you are passing myfile as an argument, and not myfile() -- and what the difference is.
A few suggestions: don't use file as the loop variable name since it ghosts the Python file builtin and at the very least makes it confusing to read quickly; Are you sure the loop does what you want? It appears to return just the first appearing .mp4 file from the list of files as os.listdir orders them. myfile does not return all of the .mp4 files.

Extracting penultimate folder name from path

Does anyone know a clever way to extract the penultimate folder name from a given path?
eg folderA/folderB/folderC/folderD
-> I want to know what the name of folderC is, I don't know the names of the other folders and there may be a variable number of directories before folderC but it's always the 2nd to last folder.
everything i come up with seems too cumbersome (eg getting name of folderD using basename and normpath, removing this from path string, and the getting folderC
cheers, -m
There isn't a good way to skip directly to portions within a path in a single call, but what you want can be easily done like so:
>>> os.path.basename(os.path.dirname('test/splitting/folders'))
'splitting'
Alternatively, if you know you'll always be on a filesystem with '/' delineated paths, you can just use regular old split() to get there directly:
>>> 'test/splitting/folders'.split('/')[-2]
'splitting'
Although this is a bit more fragile. The dirname+basename combo works with/without a file at the end of the path, where as the split version you have to alter the index
yep, there sure is:
>>> import os.path
>>> os.path.basename(os.path.dirname("folderA/folderB/folderC/folderD"))
'folderC'
That is, we find the 'parent directory' of the named path, and then extract the filename of the resulting path from that.

Remove a string (filename) from a bigger string (the whole path)

Say that I have this string "D:\Users\Zache\Downloads\example.obj" and I want to copy another file to the same directory as example.obj. How do I do this in a way that´s not hardcoded?
"example" can also be something else (user input). I'm using filedialog2 to get the big string.
This is for an exporter with a basic GUI.
os.path.dirname() gives you the directory portion of a given filename:
>>> import os.path
>>> os.path.dirname(r"D:\Users\Zache\Downloads\example.obj")
'D:\\Users\\Zache\\Downloads'
You can solve it with str.split but this should be solved with os.path.split

open file in python without file's full name?

I am trying to execute f = open('filename') in python.
However, I dont know the full name of the file. All I know is that it starts with 's12' and ends with '.ka',I know the folder where it's located, and I know it is the only file in that folder that starts and ends with "s12" and ".ka". Is there a way to do this?
Glob is your friend:
from glob import glob
filename = glob('s12*.ka')[0]
Careful though, glob returns a list of all files matching this pattern so you might want to assert that you get the file you actually want somehow.

Categories