python使用replace将数组写入txt文本

发布时间 2023-07-15 14:35:52作者: 虚生
一 概念
1 Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
2 用法:str.replace(old, new[, max])
二 源码
import numpy as np

sample_list = [23, 22, 24, 25]
new_array = np.array(sample_list)

# Displaying the array

file = open("sample.txt", "w+")

# Saving the array in a text file
content = str(new_array).replace(']','')
content = str(content).replace('[','')
file.write(content)
file.close()

# Displaying the contents of the text file
file = open("sample.txt", "r")
content = file.read()

print("Array contents in sample.txt: ", content)
file.close()