python读txt转array_np.array和txt文件的转换

np.array保存为txt

格式

numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=‘n’, header=’’, footer=’’, comments=’# ')[source]

参数

fname : filename or file handle

If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxtunderstands gzipped files transparently.

X : 1D or 2D array_like

Data to be saved to a text file.

fmt : str or sequence of strs, optional

A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. For complex X, the legal options for fmt are:

- a single specifier, fmt=’%.4e’, resulting in numbers formatted like ‘ (%s+%sj)’ % (fmt, fmt)

- a full string specifying every real and imaginary part, e.g. ‘ %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej’ for 3 columns

- a list of specifiers, one per column - in this case, the real and imaginary part must have separate specifiers, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns

delimiter : str, optional

String or character separating columns.

newline : str, optional

String or character separating lines.

header : str, optional

String that will be written at the beginning of the file.

footer : str, optional

String that will be written at the end of the file.

comments : str, optional

String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt.

参考用法

array = numpy.array([1, 2, 3, 4])

numpy.savetxt("file_name.txt" array, fmt="%f",delimiter=",")

txt文件读取到np.array

参考用法

array = numpy.loadtxt("file_name.txt")

print(array)

还有一种方法:

array = numpy.genfromtxt("file_name.txt", delimiter=',', skip_header=18)

'''skip_header忽略前多少行'''

print(array)

注意, numpy.genfromtxt也可以读取CSV文件。

原文链接:https://blog.csdn.net/weixin_42468475/article/details/105498104

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值