Reputation: 154
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)
Upvotes: 1
Views: 973
Reputation: 6600
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)
Upvotes: 3
Reputation: 175
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
Upvotes: 1
Reputation: 42796
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))
Upvotes: 3