首页 > 解决方案 > 它如何将列表中的结果保存到 .txt 文件中?

问题描述

在此代码中,脚本从“Base.txt”文件中获取所有坐标(x, y),但不幸的是,仅从第 1 行将结果保存到“Save.txt”文件中,并跳过了坐标线的其余部分列表中的值。

from ecpy.curves
import Curve,Point

with open("Base.txt", "rt") as base:
    for line in base.read().splitlines():
        x, y = map(lambda v: int(v, 16), line[1: -1].split(" , "))

cv = Curve.get_curve('secp256k1')

A  = Point(x,y,cv)

C  = 6

B  = A*C

with open("Save.txt", "w") as file:
    print(B,file=file, sep="\n")

它如何将列表中的所有结果保存到“Save.txt”文件中?

标签: pythonpython-3.xlistmath

解决方案


for 循环

with open("Base.txt", "rt") as base:
    for line in base.read().splitlines():
        x, y = map(lambda v: int(v, 16), line[1: -1].split(" , "))

覆盖每一行xy您应该在 for 循环中包含所有内容,并以“附加”模式打开文件,并在文件上使用该write函数。

from ecpy.curves
import Curve,Point

with open("Base.txt", "rt") as base:
    for line in base.read().splitlines():
        x, y = map(lambda v: int(v, 16), line[1: -1].split(" , "))

        cv = Curve.get_curve('secp256k1')
    
        A  = Point(x,y,cv)

        C  = 6

        B  = A*C

        with open("Save.txt", "a") as file:
            file.write(str(B))  # should implement the __str__ or __repr__ method
            file.write("\n")

推荐阅读