从文件读取时,两行被解释为一行

时间:2016-01-07 17:13:34

标签: python file-io

我尝试逐行读取一堆文件,并从中提取标题。

android:versionCode="9109"

虽然一些标题提取得很好,但其中一些标题与下面的行连接在一起。输出是:

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)

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] 之前,标题被完全提取出来。但是,在阅读instance33.txt;

instance33.txt

前两行被解释为一行:

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

虽然其他文件的格式相同,但这种奇怪的行为发生在33: [1, 2, 48, 4500, 200] 之后。

这是什么原因?

1 个答案:

答案 0 :(得分:1)

Windows,Linux和OS X对新行'\ n','\ n \ r','\ r'使用不同的代码。编辑也可以使用不同的代码。但是open应该识别所有类型。

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