遍历sacnnet所有子文件中存在txt文件,将txt文件的每一行最后的空格去掉
时间: 2023-11-22 08:56:16 浏览: 63
你可以使用Python的os和re模块来实现这个任务。具体实现如下:
```python
import os
import re
def remove_trailing_spaces(file_path):
"""
去除文件中每一行末尾的空格
"""
with open(file_path, 'r+') as file:
lines = file.readlines()
file.seek(0)
file.truncate()
for line in lines:
file.write(re.sub(r'\s+$', '', line) + '\n')
def traverse_directory(directory):
"""
遍历目录下所有子文件,找出txt文件并去除每行末尾空格
"""
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
remove_trailing_spaces(file_path)
# 示例
traverse_directory('/path/to/scannet')
```
这个脚本会遍历指定目录下的所有子文件,找出所有以`.txt`为后缀的文件,并对每行末尾的空格进行删除。实现过程中,我们使用了正则表达式`r'\s+$'`来匹配每行末尾的空格,然后使用`re.sub()`函数将其替换为空字符串。同时,我们使用了文件读写模式中的`'r+'`来同时读取和写入文件。
阅读全文
相关推荐










