开发者

Extracting a substring makes the for loop break in python

I am having a lot of trouble with a text file given to me that I need to parse. This is my third attempt at parsing it (I tried both C and php which seem to fail in different ways).

I have this extremely simple code :

    import fileinput

for line in fileinput.input(['basin_stclair.txt']):
    print line[0:64]

For some reason the code exits after the first print.

If I print the lines whole then it never stops but the lines are still combined. (If I only let the loop run for one iteration I get two lines(14 floats).

The text file looks like this(Several hundred lines like this one, 7 floats) :

1.749766 3.735660 0.294098 310.461737 0.000000 0.231367 0.230505

When I copy the entire text in kate it gets all jumbled and lines combine.

The text file 开发者_如何学Gowas made using excell on a windows machine. (I'm working on a linux box).

Any ideas?


You have some problem with the newline characters in your file. Try opening the file using Python's universal newline support:

for line in open('basin_stclair.txt', 'U'):
    print line[0:64]


Are you trying to print the first 64 lines? If so, try something like this:

i = 0
for line in fileinput.input(['basin_stclair.txt']):
  print line[0:64]
  if i > 63:
     break
  i = i + 1

Are you trying to print the first 64 characters of each line? Try something like this:

for line in fileinput.input(['basin_stclair.txt']):
    if len(line) > 63:
        print line[0:64]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜