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

标签 python python-3.x file python-3.7

我正在编写一个词汇程序,您可以在其中输入任意数量的单词并将其翻译成另一种语言。这些词保存在 .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/

相关文章:

python - 理解Python中DataFrame的执行

python - 在 python 中如何使用选定的 Outlook 电子邮件

python - 如何单元测试命令行参数?

python - 从文件创建参数列表的列表

c++ - 处理文件时出现 fatal error

python - 获取所有请求输入值

python - &符号在打印功能中如何工作?

python - 解决在 python 中打开 pdf 文件时的路径问题

python-3.x - python 3.x : Trying to compare current element with previous and next (without built-in functions)

php - 手动设置 $_FILES 数组并使用 move_uploaded_file 函数