I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far
def getEyeD3Tags(path):
try:
trackInfo = eyeD3.Mp3AudioFile(path)
tag = trackInfo.getTag()
tag.link(path)
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
#return (tag.getArtist(),tag.getTitle(),tag.getAlbum())
except eyeD3.InvalidAudioFormatException:
print "File %s is not a mp3 file " % path
mp3Num=0
temp=os.walk(valid-folder-name)
for root, dirs, files in temp:
for i in files:
if os.path.join(root,i):
temp=os.path.splitext(i)
temp[1].lower()
if temp[1]=='.mp3':
mp3Path=os.path.join(root,i)
print mp3Path
getEyeD3Tags(mp3Path)
mp3Num+=1
raw_input()
#print "**"
else:
print "Error invalid path"
print "\n\n"
#raw_input()
print mp3Num
raw_input()
And BTW is it a way to get genre of mp3 file using eyeD3?
Thx in advance
To check if the file being parsed is a valid mp3, call the eyeD3.isMp3File(filename) method.
The following is from a short script I made to auto-sort my music folder.
def parseIDETag(self, path):
if eyeD3.isMp3File(path):
That way, if the file isn't an mp3, it'll just skip over it.
Also, str(tag.getGenre()) returns the genre as a string using eyeD3.
Related
I am trying to print line-by-line per file that is inside a list.
At the end of each line of the file, it needs to check if the term ".sh" is in it or not.
I am getting the error
"Tail: Write error: "Broken Pipe"
Expected result:
Read each from list
Check each line of the file if the term ".sh" comes in it at the end of the line of the file.
Prints if it finds the ".sh"
This is what I have atm:
# Modules
import os
from pprint import pprint
# Files in list
dirlist = ['test.txt','test2.txt','test3.txt']
# Loop to read the file in list
for x in range (len(dirlist)):
print ("Output of Filename: " + dirlist[x]
# Variable to save the last 3 characters of the line
last3 = os.popen ("cat " + dirlist[x] + " | tail -c 3")
print last3
# Read file
f = open(dirlist[x], "r")
# Loop to check if the keyword is the same as last3
for l in f:
if last3 in l:
print ("FOUND IT!")
else:
print ("NOT IN IT!")
Outcome:
#Nic
[![enter image description here][3]][3]
I suggest that you use with environment with native python code instead of open and os.popen
Here is an example
# Files in list
dirlist = ['test.txt','test2.txt','test3.txt']
# Loop to read the file in list
for x in dirlist:
print ("Output of Filename: " + x)
with open(x) as f
lines=f.readlines()
for line in lines: #here you print each line
print (line)
if '.sh' in lines[-1:]: #check if .sh is in the last line
print("found it")
else:
print("didnt find it")
os.popen returns a file object, not a string.
See: Assign output of os.system to a variable and prevent it from being displayed on the screen
tail (actually stdio) gives the "Broken Pipe" error when it tries to write output but there's nobody around to read it. (More specifically, when it receives SIGPIPE.)
If you're going to launch a child process with popen, you need to finish reading from the pipe before your program exits.
In your case, you should probably use subprocess.run rather than a bare os.popen.
Or, better yet, don't use a subprocess for simple file operations! Just do them in native Python code, and it will be much simpler.
With the help Of #Nic Wanavit and Daniel Pyrden, I finally fixed it.
I've put the if/else inside the loop, otherwise it would check all the lines for the .sh instead of per line.
and I've put parenthesis inside the ".sh" section and that worked!
However, I did not do it in the last 3 characters, because the -1: wasn't working for me for some reason.
# Files in List
dirlist = ['test.txt', 'test2.txt', 'test3.txt']
# Loop to read the file in list
for x in dirlist:
print ("Output of filename: "+ x)
with open(x) as f:
lines = f.readlines()
for line lines:
print ("Line in file: " + line)
if (".sh" in line):
print ("FOUND IT")
else:
print ("not found it \n")
Result
I want to save a path to json file, code as below:
def writeToJasonFile(results, filename):
with open(os.path.join(filename), "w") as fp:
try:
fp.write(json.dumps(results))
except Exception as e:
raise Exception("Exception while writing results " % e)
if __name__ == '__main__':
file_path = os.getcwd()
writeToJasonFile(file_path, 'test.json')
When I open json file, the string is saved as escape str: "C:\\test\\Python Script"
How could I dump it as raw string? Saying "C:\test\Python Script"
I could do it in another way. I replace '\' with '/' for the path string and then save it. Windows is able to open the location with this format "C:/test/Python Script". If someone has the answer for the original question, please post here.
This script was posted on the interweb to insert 'silence lines' in a .srt subtitles file so that subtitles don't stay on too long, as indicated.
I can't figure out how to pass the subtitle file name; always get:
"type error: unsupported operand type(s) for %: 'NonType' and 'tuple'"
when I run with a file name after the module or
"Please provide subtitle file to process"
from the code if I don't. Is the code faulty of am I making a stupid error? Cheers.
#! /usr/bin/python
import sys;
# Patching SRT files to make them readable on Samsung TVs
# It basically inserts blank subtitles when silence should occur.
seqNo=1
try:
subs = open(sys.argv[1])
except:
print "Please provide subtitle file to process"
sys.exit(1)
while True:
srtSeqNo=subs.readline();
try:
begin,arrow,end=subs.readline().rstrip('\n\r').split(" ")
except:
break
srtText = subs.readline();
again = subs.readline();
while len(again.strip('\n\r')) > 0:
srtText = srtText + again
again = subs.readline()
print "%d\n%s --> %s\n%s" % (seqNo, begin, end, srtText)
seqNo = seqNo + 1
print "%d\n%s --> %s\n%s\n" % (seqNo, end, end, " ")
seqNo = seqNo + 1
Look after the sys.argv.
You must execute the script with the the full qualified path of your SRT file as an argument. Something like:
python script.py /home/user/folder/foo.srt
The script is functioning properly. This worked for me:
python main.py torchwood.srt
Here, my torchwood.srt file was in the same directory where the main.py file was. You can use full path of the subtitle file if it's not in the same directory.
You must pass an existing .srt file with valid contents. If the file is not found or can not be opened, it will display "Please provide subtitle file to process". So check file path and file permissions too.
I'm trying to write a program that when a user picks a file it can tell them whether it is a jpg, wav or another type (any other type goes under html). I got stuck in trying to process whether it is any of those types.
def openSoundOrPicture():
file=pickAFile()
print file
print len(file)
start=file.rfind('.')
print start
if start !=-1:
This is what I have so far but it doesn't work. (By the way, I'm really new to Python or any coding for the matter fact)
def openSoundOrPicture():
file=pickAFile()
print file
ln=len(file)
print ln
start=file.rfind('.')
print start
if start !=-1:
if file[start:ln]==".jpg"
print "File type:jpg"
elif file[start:ln]==".wav"
print "File type:wav"
You are basically trying to categorize files by their extension. Realize that there are other ways to do this like magic numbers. However, for what you asked to do, check out this code snippet:
recognized_types = ["jpg", "wav"]
default_type = "html"
file = pick_a_file()
file_extension = os.path.splitext(file)
if file_extension in recognized_types:
print "File Type: " + file_extension
else:
print "File Type: " + default_type
how can I print out a message if the action was successful?
For example:
I want to write a string to a file, and if everything was ok, it should print out an "ok" message. It is possible with an easy way?
Edit:
for root, dirs, files in os.walk('/Users'):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.'+ext:
outfile = open('log.txt', 'w')
outfile.write(fullpath)
outfile.close()
In short: python will tell you if there's an error. Otherwise, it is safe to assume everything is working (provided your code is correct)
For example:
a = "some string"
print "Variable set! a = ", a
would verify that the line a = "some string" executed without error.
You could make this more explicit like so:
try:
a = "some string"
print "Success!"
except:
print "Error detected!"
But this is bad practice. It is unnecessarily verbose, and the exception will print a more useful error message anyway.