我正在用 python
编写一个程序,我想比较文本文件中存在的两个由换行符分隔的字符串。如何读取文件并将每个字符串设置为不同的变量。即string1
和string2
?
现在我正在使用:
file = open("text.txt").read();
但这给了我额外的内容,而不仅仅是字符串。我不确定它返回什么,但这个文本文件只包含两个字符串。我尝试使用其他方法,例如 ..read().splitlines()
但这并没有产生我正在寻找的结果。我是 python 新手,所以任何帮助将不胜感激!
最佳答案
这只读取前 2 行,去掉末尾的换行符,并将它们存储在 2 个单独的变量中。它不会仅仅为了获取其中的前 2 个字符串而读取整个文件。
with open('text.txt') as f:
word1 = f.readline().strip()
word2 = f.readline().strip()
print word1, word2
# now you can compare word1 and word2 if you like
text.txt
:
foo
bar
asdijaiojsd
asdiaooiasd
输出:
foo bar
编辑:使其适用于任意数量的换行符或空格:
with open('text.txt') as f:
# sequence of all words in all lines
words = (word for line in f for word in line.split())
# consume the first 2 items from the words sequence
word1 = next(words)
word2 = next(words)
我已经验证它可以可靠地处理 text.txt
的各种“非干净”内容。
注意:我使用类似于惰性列表的生成器表达式,以避免读取超出所需数据量的数据。生成器表达式在其他方面等效于列表推导式,只不过它们延迟地生成序列中的项目,即按照要求生成尽可能多的项目。
关于python - 从文件中读取两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19225856/