如何在Python中将整数数组输出到文件?

0 投票
2 回答
5431 浏览
提问于 2025-04-18 01:32

我有一个长度为3000000的整数数组,我想把它输出到一个文件里。我该怎么做呢?

另外,这样做

for i in range(1000):
    for k in range(1000):
        (r, g, b) = rgb_im.getpixel((i, k))
        rr.append(r)
        gg.append(g)
        bb.append(b)
d.extend(rr)
d.extend(gg)
d.extend(bb)

把数组连接在一起算是个好习惯吗?

所有的数组都是这样声明的 d = array('B')

编辑:我成功地用这个方法把所有的整数用空格分隔输出了

from PIL import Image
import array

side = 500

for j in range(1000):
    im = Image.open(r'C:\Users\Ivars\Desktop\RS\Shape\%02d.jpg' % (j))
    rgb_im = im.convert('RGB')
    d = array.array('B')
    rr = array.array('B')
    gg = array.array('B')
    bb = array.array('B')
    f = open(r'C:\Users\Ivars\Desktop\RS\ShapeData\%02d.txt' % (j), 'w')
    for i in range(side):
        for k in range(side):
            (r, g, b) = rgb_im.getpixel((i, k))
            rr.append(r)
            gg.append(g)
            bb.append(b)
    d.extend(rr)
    d.extend(gg)
    d.extend(bb)
    o = ' '.join(str(t) for t in d)
    print('#', j, ' - ', len(o))
    f.write(o)
    f.close()

2 个回答

0

你想使用 tofile(),这需要你先打开一个文件对象。可以参考这两个链接了解更多信息:数组的文档文件对象的文档。另外,你有没有考虑过使用 NumPy 呢?

import array
a = array.array('B')
b = array.array('B')
a.append(3)
a.append(4)
print a
print b
with open('c:/test.dat', 'w') as f:
    a.tofile(f)
with open('c:/test.dat', 'r') as f:
    b.fromfile(f, 2)
print b

补充说明:根据你的更新,你可以将 NumPy 和 PIL 一起使用,只需一两行代码就能生成数组,而不需要循环。比如,你可以查看这个链接:Pillow 图像对象和 NumPy 数组之间的转换示例代码

1

如果你使用的是 Python 版本 2.6 或更高的版本,那么你可以使用来自 future 的打印功能!

from __future__ import print_function

#your code

# This will print out a string representation of list to the file.
# If you need it formatted differently, then you'll have to construct the string yourself
print(d, file=open('/path/to/file.txt','w')

#you can join the list items with an empty string to get only the numbers
print("".join(d),file=('/path/to/file.txt','w'))

这样做的一个副作用是,把打印从一个语句变成了一个函数,所以你需要把想要打印的内容放在 () 里面。

撰写回答