python将结果与txt文件中结果相加
时间: 2023-11-22 12:54:36 浏览: 137
txt文件合并
假设你有一个文本文件 `result.txt`,其中包含一些数字,每个数字占据一行。你想将这些数字与你的 Python 程序计算的结果相加,并将结果写回到文件中。可以按照以下步骤进行操作:
1. 读取文本文件并将其转换为数字列表:
```python
with open('result.txt', 'r') as f:
numbers = [int(line.strip()) for line in f]
```
2. 计算结果并将其与数字列表中的数字相加:
```python
result = sum(numbers) + your_calculation_result
```
3. 将结果写入文件:
```python
with open('result.txt', 'w') as f:
f.write(str(result))
```
完整代码:
```python
with open('result.txt', 'r') as f:
numbers = [int(line.strip()) for line in f]
your_calculation_result = 42
result = sum(numbers) + your_calculation_result
with open('result.txt', 'w') as f:
f.write(str(result))
```
阅读全文