有没有更像Python的方法?

2024-04-20 08:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个python脚本,请注意。在

我从《潜入Python》中拼凑出了这个,效果很好。不过,由于这是我的第一个Python脚本,因此我希望能提供一些关于如何改进它的技巧,或者可以更好地采用Python编程方式的方法。在

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)

Tags: thepathinsourceforifosdef
3条回答

代码

  • 没有描述其功能的docstring
  • 重新发明shutil.copytree的“电池”
  • 具有一个名为walkDirectory的函数,该函数不按其名称所示执行
  • {cd2>函数不包含
    • 那些get函数嵌入的高级参数比它们应该嵌入的更深
  • 非常健谈(print不管你想不想)

使用os.path.walk。它为你做了大部分的簿记工作;然后你只需要给它提供一个访问者函数来做你需要的事情。在

或者,哦,该死,看起来像os.path.walk操作系统已被弃用。然后使用os.walk,您将得到

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

正如其他人提到的,您可能希望使用内置的os模块中的walk。另外,考虑使用PEP 8 compatible style(没有驼峰大小写,而是this_stye_of_function_naming())。直接将可执行代码(即没有库/模块)包装到if __name__ == '__main__': ...块中也是一种很好的做法。在

相关问题 更多 >