繁体   English   中英

用于将文件分类到文件夹的Python代码

[英]Python code for sorting files into folders

Python 2.5.1

http://www.cgsecurity.org/wiki/After_Using_PhotoRec

我刚刚运行了PhotoRec,作为将文件类型排序到其自己的文件夹中的一种方式而给出的代码又返回了此错误。 关于如何更改的任何建议? 谢谢 :

[EDIT2:两点:

  1. 这个问题被否决了,因为它是代码的“用法”,而不是编程问题。 它可以作为编码问题吗? 我认为是。
  2. 我回过头来编辑了代码的来源页面,以阐明为了他人的利益而对参数的需求。]

    gyaresu $ python recovery.py追溯(最近一次调用):文件“ recovery.py”,第8行,源= sys.argv [1] IndexError:列表索引超出范围

脚本:

#!/usr/bin/env python
import os
import os.path
import shutil
import string
import sys

source = sys.argv[1]
destination = sys.argv[2]

while os.path.exists(source) != True:
    source = raw_input('Enter a valid source directory\n')
while os.path.exists(destination) != True:
    destination = raw_input('Enter a valid destination directory\n')

for root, dirs, files in os.walk(source, topdown=False):
    for file in files:
        extension = string.upper(os.path.splitext(file)[1][1:])
        destinationPath = os.path.join(destination,extension)

        if os.path.exists(destinationPath) != True:
            os.mkdir(destinationPath)
        if os.path.exists(os.path.join(destinationPath,file)):
            print 'WARNING: this file was not copied :' + os.path.join(root,file)
        else:
            shutil.copy2(os.path.join(root,file), destinationPath)

这仅表示程序需要两个命令行参数:source和destination。 如果希望在另一个函数中使用相同的代码,请用自己的变量替换sys.argv [1]和[2]。

或者您可以修改原始脚本并添加

if len(sys.argv) != 3:
    print "Require 2 arguments: %s <source> <destination>" %(sys.argv[0])
    sys.exit(1)

在import语句之后进行正确的错误处理。

由于脚本将询问路径是否不存在,因此可以将程序参数设为可选。

更改

source = sys.argv[1]
destination = sys.argv[2]

source = sys.argv[1] if len(sys.argv > 1) else ""
destination = sys.argv[2] if len(sys.argv > 2) else ""

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM