使用shutil复制文件时出现意外结果

时间:2014-04-29 11:42:05

标签: python-3.x shutil

我想将一个文件复制到另一个文件。根据{{​​3}}的接受答案,我做了:

def fcopy(src):
    dst = os.path.splitext(src)[0] + "a.pot"
    try:
        shutil.copy(src, dst)
    except:
        print("Error in copying " + src)
        sys.exit(0)

并将其用作:

print(atoms)
for q in range(0, len(atoms), 2):
    print(type(atoms[q]))
    print(atoms[q], fcopy(atoms[q]))

这在代码中有很多检查,但我希望只要它找到atoms[q]并不重要。但我得到的结果是:

['Mn1.pot', 'Mn2.pot']   <= result of print(atoms)
<class 'str'>            <= result of type(atoms)
Mn1.pot None             <= result of print(atoms,fcopy(atoms)). 
['Mn3.pot', 'Mn4.pot']
<class 'str'>
Mn3.pot None
['Mn5.pot', 'Mn6.pot']
<class 'str'>
Mn5.pot None
['Mn7.pot', 'Mn8.pot']
<class 'str'>
Mn7.pot None

我期待print(atoms[q], fcopy(atoms[q]))给我Mn1.pot Mn1a.pot

我仍然是python的初学者,所以如果有人能告诉我这里出了什么问题,那将会很棒。

1 个答案:

答案 0 :(得分:1)

您没有收到错误 - 如果您这样做,您会看到打印出Error in copying消息。

您需要知道的部分是每个Python函数都返回一个值。如果你不告诉Python要返回什么值,Python返回None

因此,如果您希望将目标文件返回给调用者,则必须自己执行:

def fcopy(src):
    dst = os.path.splitext(src)[0] + "a.pot"
    try:
        shutil.copy(src, dst)

        return dst   # this line should be added

    except:
        print("Error in copying " + src)
        sys.exit(0)
相关问题