怎么修改这个代码将points保存到文本文件
时间: 2023-12-06 14:45:00 浏览: 29
可以使用Python内置的文件操作来保存points到文本文件中。可以按照以下步骤进行操作:
1. 在代码中添加一个函数,将points保存到文本文件中:
```python
def save_points(points, file_path):
with open(file_path, 'w') as f:
for point in points:
f.write(f"{point[0]},{point[1]},{point[2]}\n")
```
这个函数将points列表中的每个元素(也是一个列表,包含三个值)都写入到文件中,每个元素占一行,每个值之间用逗号分隔。
2. 在主程序中调用这个函数,将points保存到文件中:
```python
file_path = "points.txt" # 指定文件路径和文件名
save_points(points, file_path) # 调用函数保存points到文件中
print(f"Points have been saved to {file_path}.")
```
这样,当程序运行完毕后,points就会被保存到名为points.txt的文本文件中。
完整代码示例:
```python
import random
def generate_points(n):
points = []
for i in range(n):
x = random.randint(0, 100)
y = random.randint(0, 100)
z = random.randint(0, 100)
points.append([x, y, z])
return points
def save_points(points, file_path):
with open(file_path, 'w') as f:
for point in points:
f.write(f"{point[0]},{point[1]},{point[2]}\n")
n = 10
points = generate_points(n)
file_path = "points.txt"
save_points(points, file_path)
print(f"Points have been saved to {file_path}.")
```