如何将指定文件的内容写入 tempfile,并修改,然后再覆盖掉原文件
时间: 2024-05-05 12:17:40 浏览: 50
自己制作的文件内容和文件名同时替换
可以使用以下步骤将指定文件的内容写入到tempfile中,并进行修改,最后再将修改后的内容覆盖原文件:
1. 导入tempfile模块,创建一个临时文件
```python
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
pass
```
2. 使用文件读取函数,将指定文件的内容读取到tempfile中
```python
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
with open('file.txt', 'r') as f:
temp_file.write(f.read())
```
3. 对tempfile中的内容进行修改
```python
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
with open('file.txt', 'r') as f:
temp_file.write(f.read())
temp_file.seek(0)
temp_file_contents = temp_file.read()
temp_file.seek(0)
temp_file.write(temp_file_contents.replace('old', 'new'))
```
4. 关闭tempfile,将修改后的内容覆盖原文件
```python
import tempfile
import shutil
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
with open('file.txt', 'r') as f:
temp_file.write(f.read())
temp_file.seek(0)
temp_file_contents = temp_file.read()
temp_file.seek(0)
temp_file.write(temp_file_contents.replace('old', 'new'))
shutil.move(temp_file.name, 'file.txt')
```
阅读全文