社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中拆分.txt文件中的行

Richard Lewis • 4 年前 • 421 次点击  

我有一个.txt文件:

My
name is
Richard

我想要一些像 ['My', 'name is', 'Richard'] 我试过了

file = open("Text.txt")
strings = file.read()
strings = strings.split()
print(strings)

但它给了我 ['My', 'name', 'is', 'Richard'] 那么我怎样才能一行一行地得到它呢?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38094
 
421 次点击  
文章 [ 3 ]  |  最新文章 4 年前
taras
Reply   •   1 楼
taras    5 年前

只是使用

strings = strings.splitlines()

而不是

strings = strings.split()

splitlines 方法按换行符拆分字符串

David Culbreth
Reply   •   2 楼
David Culbreth    5 年前

有一个集成函数 readlines() . 有一个 tutorialspoint article 关于它,它在 python docs

你可以这样使用它。

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() .

Markus Unterwaditzer
Reply   •   3 楼
Markus Unterwaditzer    5 年前

split() 按任何空白分割。使用此:

file = open("text.txt")
strings = [line.strip() for line in file]