How to delete a file or folder?

前端 未结 13 1272
青春惊慌失措
青春惊慌失措 2020-11-22 12:29

How do I delete a file or folder in Python?

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 13:16

    You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib, pathlib2).

    To remove a file there is the unlink method:

    import pathlib
    path = pathlib.Path(name_of_file)
    path.unlink()
    

    Or the rmdir method to remove an empty folder:

    import pathlib
    path = pathlib.Path(name_of_folder)
    path.rmdir()
    

提交回复
热议问题