python遍历所有.hdr文件并在第二行添加内容
时间: 2023-05-27 09:01:27 浏览: 147
以下是一个示例代码,可以遍历当前目录下所有.hdr文件,并在第二行添加指定内容:
```python
import os
# 要添加的内容
add_content = "// This is the added content."
# 遍历当前目录下所有.hdr文件
for file in os.listdir(os.getcwd()):
if file.endswith(".hdr"):
filepath = os.path.join(os.getcwd(), file)
with open(filepath, "r+") as f:
# 读取文件内容
content = f.read()
# 在第二行插入内容
lines = content.splitlines()
lines.insert(1, add_content)
new_content = '\n'.join(lines)
# 将修改后的内容写回文件
f.seek(0)
f.write(new_content)
f.truncate()
print(f"Add content to '{file}'")
```
解释一下代码的每一步:
1. 导入os模块,用于操作文件系统
2. 设置要添加的内容(这里假设要添加的是 "// This is the added content.")
3. 使用os.listdir()函数获取当前目录下的所有文件名列表
4. 使用字符串的.endswith()方法筛选出以.hdr结尾的文件名
5. 构造文件的完整路径
6. 使用带有读写权限的open()函数打开文件
7. 使用read()方法读取文件的全部内容
8. 使用splitlines()方法将内容按行拆分成列表
9. 使用insert()方法在第二行插入要添加的内容
10. 使用join()方法将列表转换为字符串,并用"\n"连接每行内容
11. 使用seek()方法将文件指针移到文件头部
12. 使用write()方法将修改后的内容写入文件
13. 使用truncate()方法截断文件,以清除可能存在的多余内容
14. 输出添加内容的消息
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)