[英]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.这些单词保存在一个.txt 文件中。 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.然后你可以在 Python 控制台中打开这个文件,程序会问你一个词,你应该输入另一种语言的翻译。 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:但是当程序询问我使用 readlines() 的词汇时,程序还会询问您语言的翻译(第一行),例如:
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:只需跳过第一行,文件 object 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)
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,您可以通过在fd
上调用next
来跳过第一行(因为文件 object 是一个迭代器),例如,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.