简体   繁体   中英

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

I am coding a vocabulary program where you can enter as many words as you want with their translation in another language. These words are saved in a.txt file. Then you can open this file inside the Python Console and the program will ask you a word and you should enter the translation in the other language. But in the first line I have the two languages and later I split them and I use them again. But when the program asks the vocabulary I use readlines() but then the program also asks you the translation of the language (first Line) for example:

German
Translation: 

but I don't want this, I want that the program reads every line in this file except of the first Line. And I don't know the amount of lines in this file, because the user enters as many word as he wants.

Thank you very much for your help: And here is my code where I read the lines:

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)

Just skip the first line, the file object file is alraedy an iterator yielding the lines:

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)

As a comprehension:

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

You could skip the first line by calling next on the fd (since file object is an iterator) like,

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)

You can add a counter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM