Python 3.7: 我怎样才能用readlines() 读取除第一行以外的整个文件?

Python 3.7: How can I read a whole file with readlines() except of the first line?

我正在编写一个词汇程序,您可以在其中输入任意数量的单词并将其翻译成另一种语言。这些词保存在 .txt 文件中。然后你可以在 Python 控制台中打开这个文件,程序会问你一个词,你应该输入另一种语言的翻译。但在第一行我有两种语言,后来我将它们分开并再次使用它们。但是当程序询问我使用 readlines() 的词汇时,程序还会询问您语言的翻译(第一行),例如:

German
Translation: 

但我不想要这个,我希望程序读取该文件中除第一行以外的每一行。而且我不知道这个文件中的行数,因为用户可以输入任意多的单词。

非常感谢您的帮助!这是我阅读这些行的代码:

with open(name + ".txt", "r") as file:
        for line in file.readlines():
            word_1, word_2 = line.split(" - ")
            newLanguage_1.append(word_1)
            newLanguage_2.append(word_2)

只需跳过第一行,文件对象 file 已经是一个产生以下行的迭代器:

with open(f"{name}.txt", "r") as file:
     next(file)
     for line in file:
         word_1, word_2 = line.split(" - ")
         newLanguage_1.append(word_1)
         newLanguage_2.append(word_2)

作为理解:

with open(f"{name}.txt", "r") as file:
     next(file)
     newLanguage_1, newLanguage_2 = zip(*(l.split(" - ") for l in file))

您可以通过在 fd 上调用 next 来跳过第一行(因为文件对象是一个迭代器),例如,

with open("{}.txt".format(name), "r") as file:
        next(file) # skip the first line in the file
        for line in file:
            word_1, _ , word_2 = line.strip().partition(" - ") # use str.partition for better string split
            newLanguage_1.append(word_1)
            newLanguage_2.append(word_2)

您可以添加一个计数器。

with open(name + ".txt", "r") as file:
    i=0
    for line in file.readlines():
        if i==0:
            pass
        else:
            word_1, word_2 = line.split(" - ")
            newLanguage_1.append(word_1)
            newLanguage_2.append(word_2)
        i+=1