Question

I want to copy one file to another. From the accepted answer of this thread, I have done:

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)

and using it as:

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

This is quite a few check down inside the code, but I expect that does not matter as long as it finds atoms[q]. But the result I am getting is:

['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

Where I was expecting the print(atoms[q], fcopy(atoms[q])) to give me Mn1.pot Mn1a.pot

I am still a beginner in python, so it will be great if someone can show me what's going wrong here.

Était-ce utile?

La solution

You are not getting an error -- if you did you would see the Error in copying message printed.

The part you need to know is that every Python function returns a value. If you do not tell Python what value to return, Python returns None.

So if you want the destination file to be returned to the caller, you have to do it yourself:

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top