0

我对python真的很陌生,现在我在做一个学生项目时遇到了一些问题。基本上我尝试从格式化为列的文本文件中读取数据。我将数据存储在列表列表中,并对数据进行排序和操作,然后再次将它们写入文件。我的问题是将写入的数据对齐在适当的列中。我发现了一些方法,例如

"%i, %f, %e" % (1000, 1000, 1000)

但我不知道会有多少列。所以我想知道是否有办法将所有列设置为固定宽度。

这是输入数据的样子:

2     232.248E-09         74.6825             2.5         5.00008         499.482
5             10.         74.6825             2.5        -16.4304           -12.3

这就是我将数据存储在列表列表中的方式:

  filename = getInput('MyPath', workdir)
  lines = []
  f = open(filename, 'r')
    while 1:
        line = f.readline()
        if line == '':
            break
        splitted = line.split()
        lines.append(splitted)            
    f.close()

为了写入数据,我首先将列表列表的所有行元素放入一个字符串中,元素之间有一个固定的空闲空间。但相反,我需要一个固定的总空间,包括元素。但我也不知道文件中的列数。

for k in xrange(len(lines)):
    stringlist=""
    for i in lines[k]:
        stringlist = stringlist+str(i)+'        '
    lines[k] = stringlist+'\n'

    f = open(workdir2, 'w')
    for i in range(len(lines)):
        f.write(lines[i])
    f.close()

这段代码基本上可以工作,但遗憾的是输出格式不正确。

非常感谢您在此问题上提供的任何帮助!

4

2 回答 2

0

字符串格式化可能是要走的路:

>>> print("%10s%9s" % ("test1", "test2"))
     test1    test2

虽然您可能希望首先从这些数字创建字符串,然后按照我上面显示的那样格式化它们。

我无法完全理解您的编写代码,但尝试以某种方式处理它:

from itertools import enumerate

with open(workdir2, 'w') as datei:
    for key, item in enumerate(zeilen):
        line = "%4i %6.6" % key, item
        datei.write(item)
于 2013-04-04T09:45:35.630 回答
0

你完全正确地开始能够像上面那样使用字符串格式化来格式化宽度。但正如您正确指出的那样,棘手的一点是为可变大小的输出列表执行此操作。相反,您可以使用 join() 函数:

output = ['a', 'b', 'c', 'd', 'e',]

# format each column (len(a)) with a width of 10 spaces
width = [10]*len(a)

# write it out, using the join() function
with open('output_example', 'w') as f:
    f.write(''.join('%*s' % i for i in zip(width, output)))

会写出:

'         a         b         c         d         e'

如您所见,格式数组width的长度由输出的长度决定len(a)。这足够灵活,您可以即时生成它。

希望这可以帮助!

于 2013-04-04T09:54:50.843 回答