How do I copy a file in Python?

前端 未结 16 2270
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:12

How do I copy a file in Python?

I couldn\'t find anything under os.

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 07:41

    Directory and File copy example - From Tim Golden's Python Stuff:

    http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

    import os
    import shutil
    import tempfile
    
    filename1 = tempfile.mktemp (".txt")
    open (filename1, "w").close ()
    filename2 = filename1 + ".copy"
    print filename1, "=>", filename2
    
    shutil.copy (filename1, filename2)
    
    if os.path.isfile (filename2): print "Success"
    
    dirname1 = tempfile.mktemp (".dir")
    os.mkdir (dirname1)
    dirname2 = dirname1 + ".copy"
    print dirname1, "=>", dirname2
    
    shutil.copytree (dirname1, dirname2)
    
    if os.path.isdir (dirname2): print "Success"
    

提交回复
热议问题