将变量与python中的文件行进行比较的问题

时间:2018-10-06 08:59:43

标签: python

我有一个文本文件,想要剪切到特定行。我有这个具有10k行的dictionary.txt,我想基于该行创建一个新的文本文件,但仅包含字典文件的前100行。到目前为止,我有这个,

with open('dictionary.txt', 'r') as f:
    with open('newdict.txt', 'w') as nd:
        match = f.readlines()[99].strip('\n')

        for line in f.readlines():
            if(line.strip('\n') == match):
                nd.write(line.strip('\n'))
                break
            nd.write(line)

该代码无效,因此我尝试摆弄它并更改一些内容。我发现第100行是“矩阵”。因此,我不是使用变量作为比较,而是使用字符串

with open('dictionary.txt', 'r') as f:
    with open('newdict.txt', 'w') as nd:
        for line in f.readlines():
            if(line.strip('\n') == 'matrix'):
                nd.write(line.strip('\n'))
                break
            nd.write(line)

那行得通! 但是为什么呢?

0 个答案:

没有答案