padawan
padawan

Reputation: 1315

Two lines are interpreted as one while reading from file

I try to read a bunch of file line by line, and extract the headers from them.

for i in range(2, 43):
    file = open('/instances/instance' + repr(i) + '.txt')
    lines = file.readlines()
    header = [int(x) for x in lines[0].split()]
    print(repr(i) + ':', header)

while some of the headers extracted fine, some of them are concatenated with the line below. The output is:

2: [1, 3, 50, 5]
3: [1, 1, 50, 5]
4: [1, 5, 75, 2]
5: [1, 6, 75, 5]
6: [1, 1, 75, 10]
7: [1, 4, 100, 2]
8: [1, 5, 100, 5]
9: [1, 1, 100, 8]
10: [1, 4, 100, 5]
11: [1, 4, 139, 5]
12: [1, 3, 163, 5]
13: [1, 9, 417, 7]
14: [1, 2, 20, 4]
15: [1, 2, 38, 40, 30]
16: [1, 2, 56, 40, 40]
17: [1, 4, 40, 40, 20]
18: [1, 4, 76, 40, 30]
19: [1, 4, 112, 40, 40]
20: [1, 4, 184, 40, 60]
21: [1, 6, 60, 40, 20]
22: [1, 6, 114, 4]
23: [1, 6, 168, 40, 40]
24: [1, 3, 51, 60, 20]
25: [1, 3, 51, 60, 20]
26: [1, 3, 51, 60, 20]
27: [1, 6, 102, 60, 20]
28: [1, 6, 102, 60, 20]
29: [1, 6, 102, 60, 20]
30: [1, 9, 153, 60, 20]
31: [1, 9, 153, 60, 20]
32: [1, 9, 153, 60, 20]
33: [1, 2, 48, 4500, 200]
34: [1, 4, 96, 4480, 195]
35: [1, 6, 144, 4460, 190]
36: [1, 8, 192, 4440, 185]
37: [1, 10, 240, 4420, 180]
38: [1, 12, 288, 4400, 175]
39: [1, 3, 72, 6500, 200]
40: [1, 6, 144, 6475, 190]
41: [1, 9, 216, 6450, 180]
42: [1, 12, 288, 6425, 170]

Until instance33.txt, the header is extracted perfectly fine. However, when reading instance33.txt;

1 2 48 4
500 200
500 200
500 200
500 200

the first two lines are interpreted as one:

33: [1, 2, 48, 4500, 200]

Although the other files are formatted just the same, this strange behavior happens after instance33.txt.

What is the reason for that?

Upvotes: 1

Views: 51

Answers (1)

furas
furas

Reputation: 142641

Windows, Linux and OS X use different code for new line '\n', '\n\r', '\r'. Editors can use different code too. But open should recognize all types.

http://docs.python.org/2/library/functions.html#open

Upvotes: 1

Related Questions