在本教程中,我们将学习如何在 首先,我们将看到使用 输出量 我们要删除的文件夹必须为空。 Python将显示警告说明文件夹不为空。 删除文件夹之前,请确保其为空。 我们可以使用 输出量 输出量 翻译自: https://mkyong.com/python/python-how-to-delete-a-file-or-folder/Python删除文件或目录。 使用os模块,在Python中删除文件或文件夹的过程非常简单。 os.remove –删除文件。 os.rmdir –删除文件夹。 shutil.rmtree –删除目录及其所有内容。 1.删除文件。
os.remove从目录中删除文件的方法 #!/usr/bin/python
import os
# getting the filename from the user
file_path = input("Enter filename:- ")
# checking whether file exists or not
if os.path.exists(file_path):
# removing the file using the os.remove() method
os.remove(file_path)
else:
# file not found message
print("File not found in the directory")Enter filename:- sample.txt
File not found in the directory 2.删除一个文件夹。
os.listdir()方法获取目录中存在的文件列表。 由此,我们可以检查文件夹是否为空。 #!/usr/bin/python
import os
# getting the folder path from the user
folder_path = input("Enter folder path:- ")
# checking whether folder exists or not
if os.path.exists(folder_path):
# checking whether the folder is empty or not
if len(os.listdir(folder_path)) == 0:
# removing the file using the os.remove() method
os.rmdir(folder_path)
else:
# messaging saying folder not empty
print("Folder is not empty")
else:
# file not found message
print("File not found in the directory")Enter folder path:- sample
Folder is not empty 3.删除目录及其所有内容。
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= input("Enter directory name: ")
try:
shutil.rmtree(mydir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))Enter directory name: d:logs
Error: d:logs - The system cannot find the path specified. 参考文献
最后
以上就是威武盼望最近收集整理的关于Python –如何删除文件或文件夹?的全部内容,更多相关Python内容请搜索靠谱客的其他文章。
发表评论 取消回复