Python3:遍历某个目录下的所有文件

代码如下:
import os, shutil

if __name__=='__main__':
    work_dir = 'C:\\Users\\HUPENG\\Desktop\\noiseRecord0313\\noiseRecord\\record'
    for parent, dirnames, filenames in os.walk(work_dir,  followlinks=True):
        for filename in filenames:
            file_path = os.path.join(parent, filename)
            print('文件名:%s' % filename)
            print('文件完整路径:%s\n' % file_path)
相关的参数说明:

work_dir:需要遍历的目录

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 下面是使用Python输出详细代码完成此功能的示例:import osdef convert_doc_to_docx(root_path): for root, dirs, files in os.walk(root_path): for file in files: if file.endswith('.doc'): # 获取当前文件的绝对路径 file_path = os.path.join(root, file) # 转换后文件的绝对路径 docx_file_path = file_path.replace('.doc', '.docx') # 调用docx转换工具进行转换 os.system("soffice --headless --convert-to docx {} --outdir {}".format(file_path, root)) # 删除原始文件 os.remove(file_path) ### 回答2: 以下是使用Python输出详细代码,完成遍历某个路径下的所有子文件夹及文件,识别所有的doc文件,并将其转换为docx的功能: ```python import os import glob from docx import Document import win32com.client as win32 def convert_doc_to_docx(filepath): # 获取文件名和扩展名 base_path, ext = os.path.splitext(filepath) # 只处理doc文件 if ext == '.doc': # 创建Word应用程序 word = win32.gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(filepath) # 生成新的文件名 docx_filepath = base_path + '.docx' # 保存为docx格式 doc.SaveAs2(docx_filepath, FileFormat=16) doc.Close() word.Quit() # 删除原有的doc文件 os.remove(filepath) print(f"{filepath} 已转换为 {docx_filepath}") def traverse_directory(path): # 遍历目录下的所有子文件夹及文件 for root, dirs, files in os.walk(path): for file in files: file_path = os.path.join(root, file) # 获取文件扩展名 ext = os.path.splitext(file_path)[1] # 只处理doc文件 if ext == '.doc': convert_doc_to_docx(file_path) # 主程序入口 if __name__ == "__main__": path = "your_directory_path" traverse_directory(path) ``` 在上述代码中,使用了`os`和`glob`库来遍历目录下的所有子文件夹及文件。使用`win32com.client`库来操作Word应用程序将doc文件转换为docx格式。`convert_doc_to_docx`函数用于对单个doc文件进行转换,并将其保存为docx格式。`traverse_directory`函数用于遍历指定路径下的所有子文件夹及文件,并调用`convert_doc_to_docx`函数来进行文件转换。在主程序入口处,通过修改`path`变量来指定要遍历目录路径。 请注意,在运行代码之前,需要先安装相应的依赖库,可以使用以下命令进行安装: ``` pip install python-docx pip install pywin32 ``` 此外,请将代码中的`your_directory_path`替换为你想要遍历目录路径。运行代码后,将会输出每个转换过的文件路径以及转换后的新文件路径 ### 回答3: import os from docx import Document def convert_to_docx(dir_path): for root, dirs, files in os.walk(dir_path): for file in files: if file.endswith(".doc"): doc_path = os.path.join(root, file) docx_path = os.path.splitext(doc_path)[0] + ".docx" document = Document(doc_path) document.save(docx_path) os.remove(doc_path) print(f"{doc_path} 转换为 {docx_path} 完成") dir_path = "待转换文件夹路径" convert_to_docx(dir_path)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值