Is there an even more pythonic approach to this?

This is my first python script, be warned.

I put this together with Dive Into Python and it works great. However, since this is my first Python script, I would appreciate any advice on how it can be improved or approximated, which might be better to use Python for programming.

import os
import shutil

def getSourceDirectory():
    """Get the starting source path of folders/files to backup"""
    return "/Users/robert/Music/iTunes/iTunes Media/"

def getDestinationDirectory():
    """Get the starting destination path for backup"""
    return "/Users/robert/Desktop/Backup/"

def walkDirectory(source, destination):
    """Walk the path and iterate directories and files"""

    sourceList = [os.path.normcase(f)
        for f in os.listdir(source)]

    destinationList = [os.path.normcase(f)
        for f in os.listdir(destination)]

    for f in sourceList:
        sourceItem = os.path.join(source, f)
        destinationItem = os.path.join(destination, f)  

        if os.path.isfile(sourceItem):
            """ignore system files"""
            if f.startswith("."):
                continue

            if not f in destinationList:
                "Copying file: " + f
                shutil.copyfile(sourceItem, destinationItem)

        elif os.path.isdir(sourceItem):
            if not f in destinationList:
                print "Creating dir: " + f
                os.makedirs(destinationItem)

            walkDirectory(sourceItem, destinationItem)

"""Make sure starting destination path exists"""
source = getSourceDirectory()
destination = getDestinationDirectory()

if not os.path.exists(destination):
    os.makedirs(destination)

walkDirectory(source, destination)
+3
source share
5 answers

, , , walk os. , , PEP 8 ( , this_stye_of_function_naming()). (.. /) if __name__ == '__main__': ....

+6

+4

os.path.walk. ; , , .

, , , os.path.walk . os.walk,

for r, d, f in os.walk('/root/path')
    for file in f:
       # do something good.
+3

os.walk. , , . , , , .

+2

, Pythonic - Python PEP8, . . 1

, . *, , , . getSourceDirectory - :

source_directory = "/Users/robert/Music/iTunes/iTunes Media/"

, , , .

if __name__ == '__main__':
    source = getSourceDirectory()
    destination = getDestinationDirectory()

    if not os.path.exists(destination):
        os.makedirs(destination)

    walkDirectory(source, destination)

try except, , , walkDirectory . :

try:
    walkDirectory(source, destination)
except IOError:
    os.makedirs(destination)
    walkDirectory(source, destination)

1 , . Python, , , . , os.walk .

+1
source

Source: https://habr.com/ru/post/1769929/


All Articles