我正在编写一个词汇程序,您可以在其中输入任意数量的单词并将其翻译成另一种语言。这些词保存在 .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)
最佳答案
您可以通过在 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)
关于 python 3.7 : How can I read a whole file with readlines() except of the first line?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200609/