用不同大小的行读取python文件

时间:2012-10-30 22:08:11

标签: python file

我尝试读取

等文件
1 1 2 3 4 5 6 6 7\n 
2 3 4 5 2 3 4 7 8 2 3\n 
3 1 2 4 2 1 4 5 6 2

类似的东西,我想重写文件,如

1 1
1 2
1 3
1 4
...
3 2

但是,我不知道如何存储不同大小的线条。基本代码如下,但必须更改dst []部分。

while 1:
        line = file1.readline()
    if not line:
        break
    src, tmp, dst[] = line.split(' ') 
    # rewrite part will be here

请帮帮我。提前谢谢。

4 个答案:

答案 0 :(得分:0)

这应该这样做:

In [1]: with open("data1.txt") as f:
   ...:     for line in f:
   ...:         spl=line.split()
   ...:         first,rest=spl[0],spl[1:]
   ...:         for x in rest:
   ...:             print first,x  # instead of printing write 
                                   # it to a file using 
                                   # write("{0} {1}\n".format(first,x)
   ...:             
   ...:             
1 1
1 2
1 3
1 4
1 5
...
...
3 6
3 2

答案 1 :(得分:0)

您要写的行是:

src, tmp, dst[] = line.split(' ') 

没有直接的方法可以做到这一点。你正在寻找所谓的模式匹配赋值,它是由几种语言(如Haskell)提供的,而不是Python。

最简单的方法是明确:

bits = line.split(' ')
src, tmp, dst = bits[0], bits[1], bits[2:]

如果您真的想要,可以通过将参数传递给函数来间接使用模式匹配:

def doStuff(src, tmp, *dst):
  # do stuff

doStuff(*line.split(' '))

答案 2 :(得分:0)

使用itertools.product(仅因为我写作时我不确定是否有一个或两个参数):

from itertools import product

with open('testing2.txt') as fin:
    for line in fin:
        items = line.split()
        first, rest = items[0], items[1:]
        for i, j in product(first, rest):
            print i, j

答案 3 :(得分:0)

 while (1):
    line = file1.readline()
    if not line:
        break
    tokens = line.split();
    for (count, token) in enumerate(tokens,start=1):
        print str(tokens[0]) + " " + str(token)