python遍历所有.hdr文件并在第二行插入内容
时间: 2023-05-27 10:01:37 浏览: 80
假设要在所有.hdr文件的第二行插入内容"hello":
```python
import os
# 定义要插入的内容
content_to_insert = "hello"
# 遍历所有.hdr文件
for root, dirs, files in os.walk(".", topdown=False):
for file_name in files:
if file_name.endswith(".hdr"):
# 打开文件,读取所有行
with open(os.path.join(root, file_name), "r") as f:
lines = f.readlines()
# 在第二行插入内容
lines.insert(1, content_to_insert + "\n")
# 重新写入文件
with open(os.path.join(root, file_name), "w") as f:
f.writelines(lines)
```
上述代码会在当前目录下遍历所有.hdr文件,并在第二行插入内容"hello",然后保存回原文件中。如果要修改要插入的内容,只需要修改`content_to_insert`变量即可。