用python输入当前路径遍历文件夹中的ts文件 转化为word文件
时间: 2023-04-01 11:03:41 浏览: 53
您好,我可以回答这个问题。您可以使用Python中的os和docx库来实现这个功能。以下是示例代码:
```python
import os
import docx
# 获取当前路径
current_path = os.getcwd()
# 遍历文件夹中的ts文件
for root, dirs, files in os.walk(current_path):
for file in files:
if file.endswith('.ts'):
# 将ts文件转化为word文件
ts_file_path = os.path.join(root, file)
doc = docx.Document()
with open(ts_file_path, 'r') as f:
text = f.read()
doc.add_paragraph(text)
doc.save(ts_file_path.replace('.ts', '.docx'))
```
这段代码将会遍历当前路径下的所有文件夹,找到所有以.ts结尾的文件,将其转化为word文件并保存在原文件所在的位置。
相关问题
用python输入当前路径遍历文件夹中和子文件夹的ts文件 转化为word文件
您好,我可以回答这个问题。您可以使用Python的os和docx库来实现这个功能。具体步骤如下:
1. 导入os和docx库
import os
from docx import Document
2. 定义一个函数,用于遍历文件夹中的ts文件并将其转化为word文件
def convert_ts_to_word(path):
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.ts'):
# 读取ts文件内容
with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
content = f.read()
# 创建word文档
doc = Document()
# 将ts文件内容写入word文档
doc.add_paragraph(content)
# 保存word文档
doc.save(os.path.join(root, file.replace('.ts', '.docx')))
3. 调用函数并传入当前路径
convert_ts_to_word(os.getcwd())
这样,当前路径下的所有ts文件都会被转化为word文件,并保存在相同的文件夹中。
用python遍历文件夹中的ts文件 转化为word文件
你好,这个问题可以使用Python的os和docx库来实现。首先,使用os库中的walk函数遍历文件夹中的ts文件,然后使用docx库将ts文件转化为word文件。具体实现可以参考以下代码:
```python
import os
from docx import Document
def ts_to_word(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.ts'):
ts_path = os.path.join(root, file)
word_path = os.path.join(root, file.replace('.ts', '.docx'))
document = Document()
with open(ts_path, 'r') as f:
for line in f:
document.add_paragraph(line.strip())
document.save(word_path)
```
其中,folder_path为要遍历的文件夹路径。使用os.walk函数遍历文件夹中的所有文件和子文件夹,如果文件名以.ts结尾,则将其转化为word文件。使用Document类创建一个空的word文档,然后读取ts文件中的内容,逐行添加到word文档中,并保存为docx格式。