Changing name of multiple files with conditions - python

I got some episodes of a show downloaded onto my PC, but the titles are mixed up completely so it's hard to find the episode I want and I don't want to refer to the wiki to find out which episode is which
Since there's a too many episodes to individually rename them, I've decided to use python to rename all at once, using a json table to store the correct episodes name to compare and replace them (the episodes all have their season number and episode number so I can use that for the comparison)
Currently, I've got this:
import os
import sys
from random import randint as mathRandom
nameDict={}
#nameDict["Ed.Edd.n.Eddy.S01E01"]={"Name":"Ed Touchables / Nagged to Ed"}
nameDict["Ed.Edd.n.Eddy.S01E02"]={"Name":"Pop Goes the Ed / Over Your Ed"}
nameDict["Ed.Edd.n.Eddy.S01E03"]={"Name":"Sir Ed-a-Lot / A Pinch to Grow an Ed"}
nameDict["Ed.Edd.n.Eddy.S01E04"]={"Name":"Dawn of the Eds / Virt-Ed-Go"}
nameDict["Ed.Edd.n.Eddy.S01E05"]={"Name":"Read All About Ed / Quick Shot Ed"}
nameDict["Ed.Edd.n.Eddy.S01E06"]={"Name":"An Ed Too Many / Ed-n-Seek"}
nameDict["Ed.Edd.n.Eddy.S01E07"]={"Name":"Look into My Eds / Tag Yer Ed"}
nameDict["Ed.Edd.n.Eddy.S01E08"]={"Name":"Fool on the Ed / A Boy and His Ed"}
nameDict["Ed.Edd.n.Eddy.S01E09"]={"Name":"It's Way Ed / Laugh Ed Laugh"}
nameDict["Ed.Edd.n.Eddy.S01E10"]={"Name":"A Glass of Warm Ed / Flea-Bitten Ed"}
nameDict["Ed.Edd.n.Eddy.S01E11"]={"Name":"Who, What, Where, Ed! / Keeping Up with the Eds"}
nameDict["Ed.Edd.n.Eddy.S01E12"]={"Name":"Eds-Aggerate / Oath to an Ed"}
nameDict["Ed.Edd.n.Eddy.S01E13"]={"Name":"Button Yer Ed / Avast Ye Eds"}
path = 'C:/Users/badfitz66/Desktop/EdEddnEddy/Episodes'
os.chdir(path)
for filename in os.listdir(path):
filename_splitext = os.path.splitext(filename)
newSettings = nameDict[filename_splitext[0]].get("Name")
if newSettings is not None :
if nameDict.get(filename_splitext[0]):
os.rename(filename, filename + str(newSettings)+'.mkv')
I'm trying to change the episodes names that are the first values (eg: Ed.Edd.n.Eddy.S01E04) to the episode number and season + the name of each part (eg: Read All About Ed / Quick Shot Ed)
But when I run, I get this error:
Traceback (most recent call last):
File "C:/Users/badfitz66/Desktop/ah.py", line 33, in <module>
os.rename(filename, filename + str(newSettings)+'.mkv')
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Ed.Edd.n.Eddy.S01E02.mkv' -> 'Ed.Edd.n.Eddy.S01E02.mkvPop Goes the Ed / Over Your Ed.mkv'
What am I doing wrong?

In your for loop, episode is a string, not a dict. So you cannot access its elements using string index.
Just replace episode['Name'] with episode, and it renamed all my files.
You can use only 1 loop to get things done
import os
import sys
nameDict={}
nameDict["test.1"]={"Name":"LOL1.mkv"}
nameDict["test.2"]={"Name":"LOL2.vcl"}
nameDict["test.3"]={"Name":"LOL3.txt"}
nameDict["test.4"]={"Name":"LOL4.py"}
nameDict["test.5"]={"Name":"LOL5.ss"}
nameDict["test.6"]={"Name":"LOL6.lol"}
nameDict["test.7"]={"Name":"LOL7.po"}
path = 'test'
# Loop over all files and directories
for filename in os.listdir(path):
# Get the name
filename_splitext = os.path.splitext(filename)
# print filename_splitext
# Check if we have new file name in nameDict
newSettings = nameDict.get( str(filename_splitext[0]), None)
if newSettings is not None :
# print newSettings
# Rename with new filename
os.rename(os.path.join(path, filename),os.path.join(path, newSettings['Name']))

Shot in the dark:
Try episode.Name instead of episode["Name"]

Related

Using Python in EventGhost

i have a script to play a random wav file from a folder works good but Il like it to only play between 9am and 5pm not sure how to do that
Thanks
from os.path import isfile, join
import random
#path you want to get wav files from
path = "C:\Windows\Media"
onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlywavfiles = []
for f in onlyfiles:
if f[-3:] == "wav":
onlywavfiles.append(f)
#generate random number based on number of available files
randomnum = random.randint(0,len(onlywavfiles)-1)
eg.plugins.System.PlaySound(path + "/" + onlywavfiles[randomnum], 1, False)
Because you did not say what triggers that script, I' ll have to guess.
I guess: The script is triggered by an event from your home automation. Perhaps someone rings the bell, or Balto requests his meal, or a fish jumps out of the aquarium.
That triggers an event and starts the script. The script plays a random wav file from the Media folder.
But you don't want the music to be played outside the interval you specified.
It doesn't matter, if the script is still executed/triggered, only the sound must not be played.
You could simply read the time, extract the hour and test 9 < hour or hour > 16
and return from the script before the sound is played if the test is true.
(I'm from Germany so we have 24 hour time. I dont know how python returns hours for 12 hr systems.)
from os.path import isfile, join
import random
import datetime
hr = datetime.datetime.now().hour
if hr < 9 or hr > 16:
exit()
#path you want to get wav files from
path = "C:\Windows\Media"
onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlywavfiles = []
for f in onlyfiles:
if f[-3:] == "wav":
onlywavfiles.append(f)
#generate random number based on number of available files
randomnum = random.randint(0,len(onlywavfiles)-1)
eg.plugins.System.PlaySound(path + "/" + onlywavfiles[randomnum], 1, False)

Python giving FileNotFoundError for file name

I was trying to iterate over the files in a directory like this:
with open(video_list, 'r') as imf:
index = []
for id, line in enumerate(imf):
video_label = line.strip().split()
video_name = video_label[0] # name of video
label = rectify_label[video_label[1]] # label of video
video_path = os.path.join(video_root, video_name) # video_path is the path of each video
### for sampling triple imgs in the single video_path ####
img_lists = os.listdir(video_path)
img_lists.sort() # sort files by ascending
img_count = len(img_lists) # number of frames in video
num_per_part = int(img_count) // 3
But Python was throwing FileNotFoundError even though the file exists:
---> 36 img_lists = os.listdir(video_path)
37 img_lists.sort() # sort files by ascending
38 img_count = len(img_lists) # number of frames in video
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/Users/m_rayeni/Emotion-FAN/Data/Train/Fear/013736360'
So what is wrong here?
I think the error here is that you are using forward Slash in the File name instead of back slash.
Your current path is "C:/Users/m_rayeni/Emotion-FAN/Data/Train/Fear/013736360"
It should be "C:\Users\m_rayeni\Emotion-FAN\Data\Train\Fear\013736360"
In all likeliness this won't work either and you would need to escape the backslash like so "C:\\Users\\m_rayeni\\Emotion-FAN\\Data\\Train\\Fear\\013736360"
Or use raw stings like - r"C:\Users\m_rayeni\Emotion-FAN\Data\Train\Fear\013736360"

Search through directory for items with multiple criteria

I'm trying to write some code that searches through a directory and pulls out all the items that start with a certain numbers (defined by a list) and that end with '.labels.txt'. This is what I have so far.
lbldir = '/musc.repo/Data/shared/my_labeled_images/labeled_image_maps/'
picnum = []
for ii in os.listdir(picdir):
num = ii.rstrip('.png')
picnum.append(num)
lblpath = []
for file in os.listdir(lbldir):
if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'):
lblpath.append(os.path.abspath(file))
Here is the error I get
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-a03c65e65a71> in <module>()
3 lblpath = []
4 for file in os.listdir(lbldir):
----> 5 if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'):
6 lblpath.append(os.path.abspath(file))
TypeError: can only concatenate list (not "str") to list
I realize the ii in picnum part won't work but I don't know how to get around it. Can this be accomplished with the fnmatch module or do I need regular expressions?
The error comes because you are trying to add ".*" (a string) to the end of picnum, which is a list, and not a string.
Also, ii in picnum isn't giving you back each item of picnum, because you are not iterating over ii. It just has the last value that it was assigned in your first loop.
Instead of testing both at once with the and, you might have a nested test that operates when you find a file matching .labels.txt, as below. This uses re instead of fnmatch to extract the digits from the beginning of the file name, instead of trying to match each picnum. This replaces your second loop:
import re
for file in os.listdir(lbldir):
if file.endswith('.labels.txt')
startnum=re.match("\d+",file)
if startnum and startnum.group(0) in picnum:
lblpath.append(os.path.abspath(file))
I think that should work, but it is obviously untested without your actual file names.

Enqueue and play a folder of .mp3s in Windows Media Player with Python

Is it possible to play all the .mp3's within a folder in windows media player?
I am using Python 3.2, and so far I have code that returns the absolute location of a random album in my music folder.
I would like to take that string and somehow open WMP and play the music within that folder
Any suggestions?
For reference, here is my code:
import random
import os
path = ["Q:\\#User\\Music\\", "Q:\\#user\\What CDs\\"]
print("You shall play " + random.sample(list(filter(lambda f: len([i for i in f if i in "."]) == 0, sum(map(lambda d: list(map(lambda e: d + "\\" + e,os.listdir(d))),list(filter(lambda c: len([i for i in c if i in "."]) == 0, sum(map(lambda a: list(map(lambda b: a + b ,os.listdir(a))), path), [])))), []) )), 1)[0])
input()
And yes, ideally that wouldn't all be in one line. I was learning how to use map and lambda and thought I'd challenge myself.
I'd now like to take this one step further, and play the random album.
Thanks!
Hmmmm, interesting idea.
I would probably create a .m3u file on the fly and then pass it to WMP as a command line argument (which, according to WMP Command Line is certainly doable).
A .m3u file is simply a text file. Here is an example .m3u for the Tool album Undertow:
#EXTM3U
#EXTINF:295,Tool - Intolerance
01 - Intolerance.mp3
#EXTINF:296,Tool - Prison Sex
02 - Prison Sex.mp3
#EXTINF:307,Tool - Sober
03 - Sober.mp3
#EXTINF:434,Tool - Bottom
04 - Bottom.mp3
#EXTINF:330,Tool - Crawl Away
05 - Crawl Away.mp3
#EXTINF:332,Tool - Swamp Song
06 - Swamp Song.mp3
#EXTINF:322,Tool - Undertow
07 - Undertow.mp3
#EXTINF:363,Tool - 4°
08 - 4°.mp3
#EXTINF:466,Tool - Flood
09 - Flood.mp3
#EXTINF:947,Tool - Disgustipated
69 - Disgustipated.mp3
Good luck!
PS - You can invoke the command line argument by importing the os module and using os.system("YOUR DOS COMMAND")
Oh, and the format used in an m3u file:
#EXTINF:<song-time-in-seconds>, <Artist> - <Song>
<Track_Num> - <File name>
If it wasn't clear.

Mac to Windows Python

I have recently moved a set of near identical programs from my mac to my school's windows, and while the paths appear to be the same (or the tail end of them), they will not run properly.
import glob
import pylab
from pylab import *
def main():
outfnam = "igdata.csv"
fpout = open(outfnam, "w")
nrows = 0
nprocessed = 0
nbadread = 0
filenames = [s.split("/")[1] for s in glob.glob("c/Cmos6_*.IG")]
dirnames = "c an0 an1 an2 an3 an4".split()
for suffix in filenames:
nrows += 1
row = []
row.append(suffix)
for dirnam in dirnames:
fnam = dirnam+"/"+suffix
lines = [l.strip() for l in open(fnam).readlines()]
nprocessed += 1
if len(lines)<5:
nbadread += 1
print "warning: file %s contains only %d lines"%(fnam, len(lines))
tdate = "N/A"
irrad = dirnam
Ig_zeroVds_largeVgs = 0.0
else:
data = loadtxt(fnam, skiprows=5)
tdate = lines[0].split(":")[1].strip()
irrad = lines[3].split(":")[1].strip()
# pull out last column (column "-1") from second-to-last row
Ig_zeroVds_largeVgs = data[-2,-1]
row.append(irrad)
row.append("%.3e"%(Ig_zeroVds_largeVgs))
fpout.write(", ".join(row) + "\n")
print "wrote %d rows to %s"%(nrows, outfnam)
print "processed %d input files, of which %d had missing data"%( \
nprocessed, nbadread)`
This program worked fine for a mac, but for windows I keep getting for :
print "wrote %d rows to %s"%(nrows, outfnam)
print "processed %d input files, of which %d had missing data"%( \
nprocessed, nbadread)
wrote 0 row to file name
processed 0 input files, of which o had missing data
on my mac i go 144 row to file...
does any one have any suggestions?
If the script doesn't raise any errors, this piece of code is most likely returning an empty list.
glob.glob("c/Cmos6_*.IG")
Seeing as glob.glob works perfectly fine with forward slashes on Windows, the problem is most likely that it's not finding the files, which most likely means that the string you provided has an error somewhere in it. Make sure there isn't any error in "c/Cmos6_*.IG".
If the problem isn't caused by this, then unfortunately, I have no idea why it is happening.
Also, when I tried it, filenames returned by glob.glob have backslashes in them on Windows, so you should probably split by "\\" instead.
Off the top of my head, it looks like a problem of using / in the path. Windows uses \ instead.
os.path contains a number of functions to ease working with paths across platforms.
Your s.split("/") should definitely be s.split(os.pathsep). I got bitten by this, once… :)
In fact, glob returns paths with \ on Windows and / on Mac OS X, so you need to do your splitting with the appropriate path separator (os.pathsep).

Categories