[英]Python: multi-line text file reading as single line
我正在尝试读取包含由换行符分隔的单词的文本文件。 但是,我似乎无法让 PyCharm 识别换行符。 我已经尝试了一切,包括更改 Line Separator settings ,但它仍然将文本文件视为单行。 有什么解决办法吗?
inFile = open("words.txt", 'r')
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
len(wordList) # returns 1
inFile = open("words.txt", 'r')
inFile.readlines() # returns 1 line containing all words
IDE:PyCharm 2018.2.4 在 macOS 上
谢谢
做这个:
with open("words.txt", "r") as file:
words = file.read().split()
print(words)
你会得到:
['AA', 'AAH', 'AAHED', 'AAHING', ......]
如果想要一个巨大的字符串中的所有单词,只需避免使用split()
方法:
with open("words.txt", "r") as file:
words = file.read()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.