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
Related
I have a set of images that I am trying to process manually, so I wrote a simple plug-in to try and help make it a little less painful. The images are numbered sequentially. So when I finish working on one image I can hit a key combo and it saves the file with the correct name and opens the next one in the list. This all works fine.
The issue I have with the plug-in is that for newly opened images the undo-redo history does not work. I am not sure if I am not loading it in correctly, or if there is something that I have to set for the undo history to be enabled. When the new image is loaded the undo history is completely blank, and when I make changes to the image nothing new is added to it as I work on the file. This makes it difficult to do anything as a mistake means starting over. I am using the latest gimp version 2.8.18.
I am a complete newb at writing gimp plug-ins and built this from web examples, so any help to figure out why this is happening would greatly appreciated. Here is the code I wrote for the plug-in:
#!/usr/bin/python
from gimpfu import *
import os.path
def get_next_filename(filepath):
#Now figure out the next image to load
old_file = filepath.replace("\\", "/")
file_info = old_file.split('/')
#print file_info
name = file_info[len(file_info) - 1].replace(".JPG", "").replace("P", "")
print name
next_num = int(name) + 1
new_name = "P" + str(next_num) + ".JPG"
print new_name
file_info[len(file_info) - 1] = new_name
s = "/"
new_path = s.join(file_info)
print new_path
return new_path
def plugin_main(timg, tdrawable):
print "orig filename: ", timg.filename
new_filename = timg.filename.replace(".JPG", "_colored.JPG")
print "new filename: ", new_filename
layer = pdb.gimp_image_merge_visible_layers(timg, CLIP_TO_IMAGE)
if not os.path.isfile(new_filename):
pdb.gimp_file_save(timg, layer, new_filename, '?')
else:
pdb.gimp_message ("Failed to save segmented image. File " + new_filename + " already exists.")
print "Closing image"
#pdb.gimp_display_delete(gimp._id2display(0))
#Try to load one of the next 5 consecutive image numbers.
#If none found then quit plugin, else load it.
new_path = timg.filename
for i in range(0,5):
new_path = get_next_filename(new_path)
if os.path.isfile(new_path):
print new_path + " found. Loading it."
img = pdb.file_jpeg_load(new_path, new_path)
pdb.gimp_display_new(img)
return
pdb.gimp_message ("No more consecutive images were found in the folder.")
register(
"segmented_saver",
"Saves a segmented image with the correct name and opens next image.",
"Saves a segmented image with the correct name and opens next image.",
"DC",
"DC",
"2016",
"<Image>/Image/Save Segmented...",
"RGB*, GRAY*",
[],
[],
plugin_main)
main()
Just call image.enable_undo(). For example:
img = pdb.gimp_file_load('R:/1.jpg','1.jpg')
gimp.Display(img)
img.enable_undo()
I have the following code:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()
The script I'm creating should be able to write to a file that the user defines via raw_input. The above could be faulty at core, open to suggestions.
Judging by the stuff the script is printing you probably want the user to input what should be printed to the file so:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
Note: This method will create the new file if it does not exist. If you want to check whether the file exists you can use the os module, something like this:
import os
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
if os.path.isfile(targetfile) == True:
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "File does not exist, do you want to create it? (Y/n)"
action = raw_input('> ')
if action == 'Y' or action == 'y':
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "No action taken"
As pointed out by others, remove the quotes from target file as you have assigned it already to a variable.
But actually instead of writing as code you can use the with open as given below
with open('somefile.txt', 'a') as the_file:
the_file.write('hello this is working!\n')
In the above case, you don't need to do any exception handling while processing the file. When-ever an error occurs the file cursor object is automatically closed and we dont need to explicitly close it. Even it writing to file it success, it will automatically close the file pointer reference.
Explanation of efficient use of with from Pershing Programming blog
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.
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.
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.