您遇到的基本问题是 csv 和固定格式基本上是相反的数据存储视图。让它们一起工作并不是常见的做法。另外,如果您只对带有空格的项目使用引号,则会破坏这些行的对齐方式:
testing "rather hmm "
strange "ways to "
"store some " "csv data "
testing testing
读回该数据也会导致错误的结果:
'testing' 'rather hmm '
'strange' 'ways to '
'store some ' 'csv data '
'testing' 'testing' ''
请注意最后一行末尾的额外字段。考虑到这些问题,我会用你的例子
"item1 " "item2 "
"next item1 " "next item2 "
"anotheritem1 " "anotheritem2 "
我发现它非常可读,很容易使用现有的 csv 库生成,并且在读回时可以正确解析。这是我用来生成它的代码:
import csv
class SpaceCsv(csv.Dialect):
"csv format for exporting tables"
delimiter = None
doublequote = True
escapechar = None
lineterminator = '\n'
quotechar = '"'
skipinitialspace = True
quoting = csv.QUOTE_MINIMAL
csv.register_dialect('space', SpaceCsv)
data = (
('testing ', 'rather hmm '),
('strange ', 'ways to '),
('store some ', 'csv data '),
('testing ', 'testing '),
temp = open(r'c:\tmp\fixed.csv', 'w')
writer = csv.writer(temp, dialect='space')
for row in data:
writer.writerow(row)
temp.close()
当然,您需要将所有数据填充到相同的长度,无论是在执行所有这些操作的函数之前,还是在函数本身中。哦,如果你有数字数据,你还必须为此留出填充余量。