简体   繁体   English

在Python中创建空间分隔文件

[英]Create Space Delimited File in Python

Using the code below, I'm getting the correct information to the file - kind of. 使用下面的代码,我得到了正确的文件信息 - 有点。 Here's the code: 这是代码:

filename = raw_input('What would you like to name the file? ')

import csv

data = [frames]
out = csv.writer(open(filename,"w"), delimiter=' ',quoting=csv.QUOTE_MINIMAL)
out.writerows(data)

This generates something that looks like this in a text file: 这会在文本文件中生成如下所示的内容:

"[255   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0]" "[  0 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171
 171 171]" 

I would like the information to look like this: 我希望这些信息看起来像这样:

255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 []0 255 255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

The 2 brackets represents a character that indicates a new row of information. 2个括号表示表示新行信息的字符。 It's a little rectangle on my text editor and I'm unsure of what the character is. 这是我文本编辑器上的一个小矩形,我不确定这个角色是什么。

So, how do I get rid of the quotes and brackets and use this other character? 那么,我如何摆脱引号和括号并使用其他字符呢?

EDIT: 编辑:

I tried using the code below and got the following error: 我尝试使用下面的代码并得到以下错误:

Traceback (most recent call last):   
  File "(stdin)", line 1, in (module)   
  File "backandforth3.py", line 154, in (module)
    out.write(' '.join(frame)) 
Type Error: sequence item 0: expect string, numpy.int32 found

I'm assuming you're using Notepad as your text editor? 我假设您使用记事本作为文本编辑器? Unix-style newlines ( \\n ) show up as boxes in Notepad because it only supports Windows newlines ( \\r\\n ). Unix风格的换行符( \\n )在记事本中显示为框,因为它只支持Windows换行符( \\r\\n )。 That said, this should provide the output you're expecting: 也就是说,这应该提供您期望的输出:

filename = raw_input('What would you like to name the file? ')

with open(filename, 'wb') as out:
    for frame in frames:
        out.write(' '.join(str(num) for num in frame))
        out.write('\r\n')

There's no reason to wrap frames in another list; 没有理由将frames包装在另一个列表中; assuming that variable is a list of lists of numbers, as the expected output would indicate, this should work fine. 假设变量是一个数字列表列表,正如预期的输出所示,这应该可以正常工作。

Also, if you absolutely have to have the "boxes" that you described in the output, replace '\\r\\n' with '\\n' . 此外,如果您必须拥有输出中描述的“框”,请将'\\r\\n'替换为'\\n'

If frames is a numpy array than you could use numpy.savetxt() function: 如果frames是一个numpy数组,你可以使用numpy.savetxt()函数:

numpy.savetxt(filename, frames)

To fix your csv code open the file in binary mode wb to avoid corrupting end of lines, and don't wrap frames in another list it seems to be already a 2D array: 要修复你的csv代码,请以二进制模式wb打开文件以避免破坏行尾,并且不要将frames包装在另一个列表中它似乎已经是一个2D数组:

import csv

with open(filename,"wb") as f:
    writer = csv.writer(f, delimiter=' ', quoting=csv.QUOTE_MINIMAL)
    writer.writerows(frames)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM