You are not logged in.

#1 2016-04-08 14:05:27

dewillepl
Member
Registered: 2016-02-12
Posts: 13

Python repeat loop

Hi,

I'm writing my first Python script to rename video and subtitles in my movies library. It works but i have problem with repeat whole function. It just do the job and exit.

#!/usr/bin/python
#

import os, sys, glob, readline

readline.set_completer_delims('')
readline.parse_and_bind("tab: complete")

def rnaming():
    fnames = os.listdir( path )
    os.chdir( path )
    dirname = os.getcwd().split(os.sep)[-1]
    tup1 = ('.mp4' '.mkv' '.avi' '.mov' '.rmvb' '.mpg' '.txt' '.sub' '.srt' )

    for files in fnames:
        if files.endswith( '.mp4' ):
            os.rename( files, dirname + '.mp4' )
        if files.endswith( '.avi'):
            os.rename( files, dirname + '.avi' )
        if files.endswith( '.mkv'):
            os.rename( files, dirname + '.mkv' )
        if files.endswith( '.txt' ):
            os.rename( files, dirname + '.txt' )
        if files.endswith( '.srt'):
            os.rename( files, dirname + '.srt' )
        if files.endswith( '.sub'):
            os.rename( files, dirname + '.sub' )
        if files.endswith( '.jpg' ):
            os.remove ( files )
        if files.endswith( '.pdf' ):
            os.remove ( files )
        
usrdir = '/home/user/Videos/'
os.system('clear')
os.chdir( usrdir )
path = input("Provide path to movie folder: ")
rnaming()

With the "while" statement it just freeze doing the job.

while True:
        for files in fnames:
            if files.endswith( '.mp4' ):
                os.rename( files, dirname + '.mp4' )

How can i fix that ??
Thanks

Offline

#2 2016-04-08 15:58:08

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 19,791

Re: Python repeat loop

The second example will never exit.  It just does the for clause over and over.
unrelated comment: You may want to investigate os.path and its methods.  (Edit: same for os.walk)

What it appears that program will do is rename every file that ends with one of those extensions to the name of the directory the file is in plus the extension.  What if you had two files in path named a.avi and b.avi.  Did you really want to name them both path.avi?  Seems like a bad idea to me.

I also see you created tup1.  I think this is where you are going, but you should iterate over tup1 inside the for files in fnames: clause and loose the multiple if statements. 

Here is a check of code from the project on I am currently working that walks a directory tree:

def HashDir(thePath):

    """ Obtain hash for contents of all files in a directory tree

    theURL:  A string that specifies the top directory tree 
 
    returns: None
    """

    logging.debug("Adding %s to database"%thePath)
    for root, dirs, files in os.walk(thePath):
        for theFile in files:
            theFilePath = os.path.abspath("%s/%s"%(root,theFile))
            if (theDatabase):
                theDatabase.write(HashFile(theFilePath),theFilePath)

Edit: 

If you have a while true:
you will need a break to get out.  This will break out on the second pass

while true:
     if not a:
          a=true
     else:
          break

Last edited by ewaller (2016-04-08 16:06:20)


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#3 2016-04-08 17:20:57

dewillepl
Member
Registered: 2016-02-12
Posts: 13

Re: Python repeat loop

I've changed code and it works now.
Good point with the 'path'. I just started to write this script and even learn Python, and this is another case to work on. My goal is to rename video files and subtitles files the same name as folder they are located. It doesn't work for ie. directory with TV Series episodes at the moment. Will take a look on your code. Thanks

import os, sys, glob, readline
readline.set_completer_delims('')
readline.parse_and_bind("tab: complete")

def rnaming():
    while True:
        usrdir = '/home/user/Videos/'
        os.system('clear')
        os.chdir( usrdir )
        path = input("Provide path to movie folder: ")
        fnames = os.listdir( path )
        os.chdir( path )
        dirname = os.getcwd().split(os.sep)[-1]
        tup1 = ('.mp4' '.mkv' '.avi' '.mov' '.rmvb' '.mpg' '.txt' '.sub' '.srt' )
        for files in fnames:
                if files.endswith( '.mp4' ):
                    os.rename( files, dirname + '.mp4' )
                if files.endswith( '.avi'):
                    os.rename( files, dirname + '.avi' )
                if files.endswith( '.mkv'):
                    os.rename( files, dirname + '.mkv' )
                if files.endswith( '.txt' ):
                    os.rename( files, dirname + '.txt' )
                if files.endswith( '.srt'):
                    os.rename( files, dirname + '.srt' )
                if files.endswith( '.sub'):
                    os.rename( files, dirname + '.sub' )
                if files.endswith( '.jpg' ):
                    os.remove ( files )
                if files.endswith( '.pdf' ):
                    os.remove ( files )
                    continue
        
rnaming() 

Last edited by dewillepl (2016-04-08 17:27:09)

Offline

#4 2016-04-08 18:36:16

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 19,791

Re: Python repeat loop

How about:

        tup1 = ('.mp4' '.mkv' '.avi' '.mov' '.rmvb' '.mpg' '.txt' '.sub' '.srt' )
        for files in fnames:
               for ext in tup1
                    if files.endswith(ext):
                          os.rename( files, dirname%s"%ext )

BTW, the 'continue' in your code does nothing.  It is the last statement before you fall through anyway

Last edited by ewaller (2016-04-08 18:37:20)


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#5 2016-04-08 22:13:54

bulletmark
Member
From: Brisbane, Australia
Registered: 2013-10-22
Posts: 653

Re: Python repeat loop

@ewaller, should add a break after your rename to make it a little more efficient.

Offline

#6 2016-04-09 00:18:01

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 19,791

Re: Python repeat loop

Good catch big_smile


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#7 2016-04-09 11:51:58

whitie
Member
Registered: 2011-03-13
Posts: 21

Re: Python repeat loop

@dewillepl: os.chdir is not a good solution. Also the many if's are not necessary.

Not tested:

RENAME = ('.mp4', '.mkv', '.avi', '.mov', '.rmvb', '.mpg', '.txt', '.sub',
          '.srt')
DELETE = ('.jpg', '.pdf')


def rnaming2(startdir=os.path.expanduser('~')):
    while True:
        input_path = input('Provide path to movie folder: ')
        if not input_path.strip():
            break
        path = os.path.join(startdir, input_path)
        items = os.listdir(path)
        dirname = os.path.dirname(path)
        for item in items:
            ext = os.path.splitext(item)[1]
            if ext in RENAME:
                os.rename(os.path.join(path, item),
                          os.path.join(path, '{}{}'.format(dirname, ext)))
            elif ext in DELETE:
                os.remove(path, item)

Whitie

Edit: splitext() had the wrong index. Fixed.

Last edited by whitie (2016-04-09 12:03:36)

Offline

#8 2016-04-12 09:29:30

Knight
Member
From: ShenZhen/Asia
Registered: 2015-11-19
Posts: 18

Re: Python repeat loop

Is Python  popular in the USA?  is python a textbook in Pasadena, CA?

Offline

Board footer

Powered by FluxBB