dir))... for file in files:... print(os.path.join(root,file))...root:testtestest-1testest-2testest.txtroot:testest-1testest-1est-1.txtroot:testest-2testest-2est-2.txt复制代码
使用 os.remove() 函数删除文件 语法格式:os.remove(path, *, dir_fd = None)path – 文件对象的相对或绝对路径,通常采用字符串格式。dir_fd – 表示文件位置的文件夹。默认值为 none,对于绝对路径,则忽略此值。删除文件之前检查文件是否存在,如果在路径中找不到该文件,则会引发 FileNotFoundError,因此...
完整代码 importosdefremove_dir(path):# 获取目录下的子文件和子目录forfileinos.listdir(path):# 拼接子文件或子目录的路径file_path=os.path.join(path,file)ifos.path.isfile(file_path):# 是文件,直接删除os.remove(file_path)else:# 是目录,递归删除remove_dir(file_path)# 删除空目录os.rmdir(path)...
os.remove(os.path.join(root, name))# 删除文件# 第二步:删除空文件夹fornameindirs: os.rmdir(os.path.join(root, name))# 删除一个空目录# 加这段代码,最外层文件夹也一起删除ifos.path.exists(dir_path): os.rmdir(dir_path) delete_dir2('data') 如果需要把最外层目录一起删除,可以加上这句 ...
for allDir in pathDir: child = os.path.join('%s%s' % (filepath, allDir)) fileName=child.replace(filepath,'') list.append(fileName) return list if __name__ == '__main__': rtf=RemoveTagFile() #以下表示只删除D:\Test\目录下的a文件夹、a.txt文件、b.txt文件 ...
以下是remove()方法删除Python文件的语法: os.remove(path) 参数 path—— 这是要删除的路径或文件名。 返回值 remove()方法没有返回值。 我们来看一些使用os.remove函数删除Python文件的示例。 示例1:使用OS.Remove()方法删除文件的基本示例。 # Importing the os libra...
path="C:\\A\\"keyword="A1"for root,dirs,filesinos.walk(path):for dirindirs:if keywordindir:rmpath=os.path.join(root,dir)print("删除文件夹: %s"%rmpath)shutil.rmtree(rmpath)for fileinfiles:if keywordinfile:rmpath=os.path.join(root,file)print("删除文件: %s"%rmpath)os.remove(rmpath) ...
os.remove(path)函数用于删除一个文件。如果文件不存在,会抛出FileNotFoundError异常。 实例 os.remove("file_to_delete.txt") 7. 重命名文件或目录 os.rename(src, dst)函数用于重命名文件或目录。src是原始路径,dst是新的路径。 实例 os.rename("old_name.txt","new_name.txt") ...
file_path = os.path.join(root, name) try: os.remove(file_path) print(f"文件 {file_path} 已成功删除") except OSError as e: print(f"删除文件 {file_path} 时发生错误: {e.strerror}") for name in dirs: dir_path = os.path.join(root, name) ...
'] # 第一步:删除文件 for name in files: os.remove(os.path.join(root, name)) # 删除文件 # 第二步:删除空文件夹 for name in dirs: os.rmdir(os.path.join(root, name)) # 删除一个空目录if __name__ == '__main__': dir_path = Path('./log').absolute() del_files2(dir_path...