我有一个.txt文件:
My name is Richard
我想要一些像 ['My', 'name is', 'Richard'] 我试过了
['My', 'name is', 'Richard']
file = open("Text.txt") strings = file.read() strings = strings.split() print(strings)
但它给了我 ['My', 'name', 'is', 'Richard'] 那么我怎样才能一行一行地得到它呢?
['My', 'name', 'is', 'Richard']
只是使用
strings = strings.splitlines()
而不是
strings = strings.split()
splitlines 方法按换行符拆分字符串
splitlines
有一个集成函数 readlines() . 有一个 tutorialspoint article 关于它,它在 python docs 也
readlines()
你可以这样使用它。
with open('path/to/my/file') as myFile: for line in myFile.readlines(): print line
直接从 docs themselves 至少从python 3.5到3.7,
如果要读取列表中文件的所有行,也可以使用 list(f) 或_ f.readlines() .
list(f)
f.readlines()
split() 按任何空白分割。使用此:
split()
file = open("text.txt") strings = [line.strip() for line in file]