str(i).endswith('doc','docx')
时间: 2023-08-04 15:09:14 浏览: 158
字符串的 `endswith()` 方法只接受一个参数,即要匹配的后缀字符串。如果你要同时匹配多个后缀,可以将它们放在一个元组中,然后使用 `endswith()` 方法进行匹配,例如:
```python
if i.endswith(('doc', 'docx')):
# do something
```
这样,如果字符串 `i` 的结尾是 `'doc'` 或者 `'docx'`,就会返回 True,执行相应的操作。
相关问题
使用python编写代码将一个文件夹下的所有子文件夹下的.sv文件按照文件名称为model.docx的文件格式转化为与.sv同名的.docx的文件,页眉写上该.SV文件的名称,并写上行号,每页50行
好的,可以使用python内置的os和docx模块来完成这个任务。以下是一个示例代码,注释中有详细的解释:
```python
import os
from docx import Document
# 设置每页的行数
ROWS_PER_PAGE = 50
# 遍历文件夹及其子文件夹下的所有.sv文件
for root, dirs, files in os.walk('.'):
for filename in files:
if filename.endswith('.sv'):
# 构造.docx文件名
docx_filename = os.path.splitext(filename)[0] + '.docx'
# 创建docx文档对象
doc = Document()
# 添加页眉
header = doc.sections[0].header
header.paragraphs[0].add_run(filename)
# 打开.sv文件并逐行读取
with open(os.path.join(root, filename), 'r') as f:
line_count = 0
for line in f:
# 每50行添加一个分页符
if line_count % ROWS_PER_PAGE == 0 and line_count > 0:
doc.add_page_break()
# 添加行号和文本内容
p = doc.add_paragraph()
p.add_run(str(line_count + 1) + ' ').bold = True
p.add_run(line.strip())
# 更新行数计数器
line_count += 1
# 保存.docx文件
doc.save(docx_filename)
```
注意,这个代码需要将文件夹中的所有.sv文件都转换为.docx文件,如果只需要转换某个文件夹下的文件,可以将`os.walk('.')`改为`os.walk('path/to/folder')`。另外,由于每个.docx文件都是新创建的,因此如果该文件名已存在,会覆盖原有文件。
用python写一个遍历文件夹及子文件夹中所有doc/docx文件并且替换其中指定汉字的函数
在Python中,你可以使用`os`模块来遍历文件夹及其子文件夹,并结合`pathlib`库来处理文件路径,`openpyxl`或`python-docx`库来操作`.doc`或`.docx`文档。这里是一个基础的函数示例,它会查找并替换指定的汉字:
```python
import os
from typing import List
import docx
def replace_char_in_doc_files(root_folder: str, target_char: str, replacement_char: str) -> List[str]:
replaced_files = []
# 遍历文件夹及其子文件夹
for dirpath, _, filenames in os.walk(root_folder):
for filename in filenames:
if filename.endswith(('.doc', '.docx')):
file_path = os.path.join(dirpath, filename)
try:
# 打开文档
with docx.Document(file_path) as doc:
# 搜索并替换目标字符
for paragraph in doc.paragraphs:
text = paragraph.text
new_text = text.replace(target_char, replacement_char)
# 如果文本有变化,保存新的文档
if text != new_text:
new_file_name = f"{filename}_replaced_{target_char}_{replacement_char}"
new_file_path = os.path.join(dirpath, new_file_name)
doc.save(new_file_path)
replaced_files.append(new_file_path)
except Exception as e:
print(f"Error processing {file_path}: {e}")
return replaced_files
# 使用函数
root_folder = 'your_directory_path' # 替换为你的文件夹路径
target_char = '原字符' # 要替换的目标字符
replacement_char = '新字符' # 替换的新字符
replaced_files = replace_char_in_doc_files(root_folder, target_char, replacement_char)
阅读全文
相关推荐

















