这是我的第一个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)
代码
walkDirectory
的函数,该函数不按其名称所示执行print
不管你想不想)使用os.path.walk。它为你做了大部分的簿记工作;然后你只需要给它提供一个访问者函数来做你需要的事情。在
或者,哦,该死,看起来像os.path.walk操作系统已被弃用。然后使用os.walk,您将得到
正如其他人提到的,您可能希望使用内置的
os
模块中的walk
。另外,考虑使用PEP 8 compatible style(没有驼峰大小写,而是this_stye_of_function_naming()
)。直接将可执行代码(即没有库/模块)包装到if __name__ == '__main__': ...
块中也是一种很好的做法。在相关问题 更多 >
编程相关推荐