【问题标题】:Python 3.7: How can I read a whole file with readlines() except of the first line?Python 3.7:除了第一行之外,如何使用 readlines() 读取整个文件?
【发布时间】:2019-10-02 19:46:17
【问题描述】:

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

【问题讨论】:

  • with open('..') as f:..next(f); for line in f:..
  • 你可以跳过fd使用next(fd)的第一行
  • 你能做一个格式化的例子吗?我不太明白你是什么意思

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


【解决方案1】:

您可以通过在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)

【讨论】:

  • 是的,当你需要split 一些str 时,使用str.partition 而不是str.split,所以你总是可以期待 3 个项目而不是一些未知数量的项目 :)
  • 你的意思是我可以拥有一定数量的物品?
  • 不,您将始终获得带有str.partition 的3 个项目,因此您可以像word1, _, word2 = 'foo bar'.partition(' ') 那样做,您将在word 和@987654333 中准确获得foobar @分别
  • 我只是用 next() 跳过第一行,对吗?不管有多少行,它都会每隔一行读取一次?
  • 是的,for 循环耗尽了 fd,因为它逐行读取直到 EOF
【解决方案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))

【讨论】:

    【解决方案3】:

    您可以添加一个计数器。

    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
    

    【讨论】:

    • 这也可能是一个解决方案,但我认为 next() 方法更容易!无论如何谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多