Need convert function output to string from use as an arguement Python - 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.

Related

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

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:

How to pull a substring off a string without knowing what the string is (file path)

I have a given file path. For example, "C:\Users\cobyk\Downloads\GrassyPath.jpg". I would like to pull in a separate string, the image file name.
I'm assuming the best way to do that is to start from the back end of the string, find the final slash and then take the characters following that slash. Is there a method to do this already or will I have search through the string via a for loop, find the last slash myself, and then do the transferring manually?
The pathlib module makes it very easy to access individual parts of a file path like the final path component:
from pathlib import Path
image_path = Path(r"C:\Users\cobyk\Downloads\GrassyPath.jpg")
print(image_path.name) # -> GrassyPath.jpg
You can certainly search manually as you've suggested. However, the Python standard library already has, as you suspected, a function which does this for you.
import os
file_name = os.path.basename(r'C:\Users\cobyk\Downloads\GrassyPath.jpg')

Extracting all file names in python

I have a application that converts from one photo format to another by inputting in cmd.exe following: "AppConverter.exe" "file.tiff" "file.jpeg"
But since i don't want to input this every time i want a photo converted, i would like a script that converts all files in the folder. So far i have this:
def start(self):
for root, dirs, files in os.walk("C:\\Users\\x\\Desktop\\converter"):
for file in files:
if file.endswith(".tiff"):
subprocess.run(['AppConverter.exe', '.tiff', '.jpeg'])
So how do i get the names of all the files and put them in subprocess. I am thinking taking basename (no ext.) for every file and pasting it in .tiff and .jpeg, but im at lost on how to do it.
I think the fastest way would be to use the glob module for expressions:
import glob
import subprocess
for file in glob.glob("*.tiff"):
subprocess.run(['AppConverter.exe', file, file[:-5] + '.jpeg'])
# file will be like 'test.tiff'
# file[:-5] will be 'test' (we remove the last 5 characters, so '.tiff'
# we add '.jpeg' to our extension-less string
All those informations are on the post I've linked in the comments o your original question.
You could try looking into os.path.splitext(). That allows you to split the file name into a tuple containing the basename and extension. That might help...
https://docs.python.org/3/library/os.path.html

How to input multiple files from a directory

First and foremost, I am recently new to Unix and I have tried to find a solution to my question online, but I could not find a solution.
So I am running Python through my Unix terminal, and I have a program that parses xml files and inputs the results into a .dat file.
My program works, but I have to input every single xml file (which number over 50) individually.
For example:
clamshell: python3 my_parser2.py 'items-0.xml' 'items-1.xml' 'items-2.xml' 'items-3.xml' .....`
So I was wondering if it is possible to read from the directory, which contains all of my files into my program? Rather than typing all the xml file names individually and running the program that way.
Any help on this is greatly appreciated.
import glob
listOffiles = glob.glob('directory/*.xml')
The shell itself can expand wildcards so, if you don't care about the order of the input files, just use:
python3 my_parser2.py items-*.xml
If the numeric order is important (you want 0..9, 10-99 and so on in that order, you may have to adjust the wildcard arguments slightly to guarantee this, such as with:
python3 my_parser2.py items-[0-9].xml items-[1-9][0-9].xml items-[1-9][0-9][0-9].xml
python3 my_parser2.py *.xml should work.
Other than the command line option, you could just use glob from within your script and bypass the need for command arguments:
import glob
filenames = glob.glob("*.xml")
This will return all .xml files (as filenames) in the directory from which you are running the script.
Then, if needed you can simply iterate through all the files with a basic loop:
for file in filenames:
with open(file, 'r') as f:
# do stuff to f.

How to loop through the list of .tar.gz files using linux command in python

Using python 2.7
I have a list of *.tat.gz files on a linux box. Using python, I want to loop through the files and extract those files in a different location, under their respective folders.
For example: if my file name is ~/TargetData/zip/1440198002317590001.tar.gz
then I want to untar and ungzip this file in a different location under its
respective folder name i.e. ~/TargetData/unzip/1440198002317590001.
I have written some code but I am not able to loop through the files. In a command line I am able to untar using $ tar -czf 1440198002317590001.tar.gz 1440198002317590001 command. But I want to be able to loop through the .tar.gz files. The code is mentioned below. Here, I’m not able to loop just the files Or print only the files. Can you please help?
import os
inF = []
inF = str(os.system('ls ~/TargetData/zip/*.tar.gz'))
#print(inF)
if inF is not None:
for files in inF[:-1]:
print files
"""
os.system('tar -czf files /unzip/files[:-7]')
# This is what i am expecting here files = "1440198002317590001.tar.gz" and files[:-7]= "1440198002317590001"
"""
Have you ever worked on this type of use case? Your help is greatly appreciated!! Thank you!
I think you misunderstood the meaning of os.system(), that will do the job, but its return value was not expected by you, it returns 0 for successful done, you can not directly assign its output to a variable. You may consider the module [subprocess], see doc here. However, I DO NOT recommend that way to list files (actually, it returns string instead of list, see doc find the detail by yourself).
The best way I think would be glob module, see doc here. Use glob.glob(pattern), you can put all files match the pattern in a list, then you can loop it easily.
Of course, if you are familiar with os module, you also can use os.listdir(), os.path.join(), or even os.paht.expanduser() to do this. (Unlike glob, it only put filenames without fully path into a list, you need to reconstruct file path).
By the way, for you purpose here, there is no need to declare an empty list first (i.e. inF = [])
For unzip file part, you can do it by os.system, but I also recommend to use subprocess module instead of os.system, you will find the reason in the doc of subprocess.
DO NOT see the following code, ONLY see them after you really can not solve this by yourself.
import os
import glob
inF = glob.glob('~/TargetData/zip/*.tar.gz')
if inF:
for files in inF:
# consider subprocess.call() instead of os.system
unzip_name = files.replace('zip', 'unzip')[:-7]
# get directory name and make sure it exists, otherwise create it
unzip_dir = os.path.dirname(unzip_name)
if not os.path.exists(unzip_dir):
os.mkdir(unzip_dir)
subprocess.call(['tar -xzf', files, '-C', unzip_name])
# os.system('tar -czf files /unzip/files[:-7]')

Categories