我有python中的浮点数列表。我想把一些列表保存在txt文件中,我按原样一个列表一个列表地阅读它们。但是在我写了下面的代码之后,我发现str(I)转换了一个str中的每个数字。我不能像它们写的那样好地读取它们。Ps我有10,000个结果列表,所以我想将每个列表保存在一行中。
result = [-0.33434,0.4434, 4343....]
with open("out.txt", w) as out:
for i in result:
out.write(str(i)+' ')
out.write("n")
更新答案
对于多个列表,将它们全部放在一个列表中,并将其写入pkl/txt文件。
import pickle
import numpy as np
results = [
[1.456,2.245,-3.441],
[4.53, 4.55, 1.22]
]
np.savetxt("results.txt", results) # write
#read
result = np.loadtxt("results.txt")
print(result.tolist())
如果您希望将名称与您的列表相关联,请考虑使用dict
。但是,您只能使用pickle
。
import pickle
results = {
"result1": [1.456,2.245,-3.441],
"result2": [4.53, 4.55, 1.22],
}
# write
with open("results.pkl", "wb") as resultFile:
pickle.dump(results, resultFile)
# read
with open("results.pkl", "rb") as resultFile:
result = pickle.load(resultFile)
print(result)
原始回答
使用pickle
或numpy
,因为它们更适合此任务。
使用pickle
:
import pickle
result1 = [1.456,2.245,-3.441]
# write
with open("result1.pkl", "wb") as resultFile:
pickle.dump(x, resultFile)
# read
with open("result1.pkl", "rb") as resultFile:
result = pickle.load(resultFile)
print(result)
使用numpy
:
import numpy as np
result1 = [1.456,2.245,-3.441]
np.savetxt("result1.txt", result1) # write
#read
result = np.loadtxt("result1.txt")
print(result.tolist())
如果您不想使用库来完成此操作,您可以简单地将每个列表用已知的分隔符join
,然后将结果字符串写入文件。
allResults
的列表列表,其格式为
allResults = [
[-0.332,434,0.4434,4865],
[9.456,-0.540,-7.06540,5.05453],
# ... and so on
]
separator = ","
with open("out.txt", "w") as out_file:
for l in allResults:
out_string = separator.join(str(x) for x in l) + "n"
out_file.write(out_string)
现在,out.txt
包含:
-0.332,434,0.4434,4865
9.456,-0.54,-7.0654,5.05453
然后读取文件,你可以读取每一行,用分隔符拆分它,将拆分字符串的每个元素转换为浮点数,并将新列表放入列表的列表中:
all_lists = []
with open("out.txt", "r") as in_file:
for line in in_file:
new_list = [float(x) for x in line.split(separator)]
all_lists.append(new_list)
现在你的列表列表回来了:
all_lists: [[-0.332, 434.0, 0.4434, 4865.0], [9.456, -0.54, -7.0654, 5.05453]]
如果您想再读一遍,请读取该行并以' '(空格)分隔。这将为您提供浮点数的字符串表示形式。之后,您可以使用float(num)方法将其转换回数字