如何批量将一个文件夹中的.xml文件转换成.txt文件
时间: 2024-05-09 16:15:12 浏览: 150
可以使用Python的os和glob库来实现批量转换。具体步骤如下:
1. 导入os和glob库:
```python
import os
import glob
```
2. 设置文件夹路径和文件格式:
```python
folder_path = 'path/to/folder'
file_format = '*.xml'
```
3. 遍历文件夹,找到所有符合格式的文件:
```python
files = glob.glob(os.path.join(folder_path, file_format))
```
4. 循环遍历所有文件,将.xml文件转换成.txt文件:
```python
for file in files:
# 获取文件名和后缀名
filename, ext = os.path.splitext(file)
# 将.xml文件转换成.txt文件
if ext == '.xml':
with open(file, 'r', encoding='utf-8') as f:
content = f.read()
with open(filename + '.txt', 'w', encoding='utf-8') as f:
f.write(content)
```
完整代码如下:
```python
import os
import glob
folder_path = 'path/to/folder'
file_format = '*.xml'
files = glob.glob(os.path.join(folder_path, file_format))
for file in files:
filename, ext = os.path.splitext(file)
if ext == '.xml':
with open(file, 'r', encoding='utf-8') as f:
content = f.read()
with open(filename + '.txt', 'w', encoding='utf-8') as f:
f.write(content)
```
将代码保存为.py文件,然后在终端中运行即可。
阅读全文