简体   繁体   English

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

[英]split lines in .txt file in python

I have a .txt file: 我有一个.txt文件:

My
name is
Richard

And I want to get something like ['My', 'name is', 'Richard'] I tried 我想得到类似我尝试过的['My', 'name is', 'Richard']

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

But it gives me ['My', 'name', 'is', 'Richard'] So how can I get it line by line? 但这给了我['My', 'name', 'is', 'Richard']那么如何才能逐行获取呢?

split() splits by any whitespace. split()被任何空格分割。 Use this: 用这个:

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

There's an integrated function for this called readlines() . 为此有一个集成函数,称为readlines() There is a tutorialspoint article about it, and it's in the python docs as well 一篇关于它的tutorialspoint文章 ,它也在python文档

You would use it like so. 您将像这样使用它。

with open('path/to/my/file') as myFile:
    for line in myFile.readlines():
        print line

And straight from the docs themselves , from at least Python 3.5 to 3.7, 直接从文档本身开始 ,至少从Python 3.5到3.7,

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines() . 如果要读取列表中文件的所有行,也可以使用list(f)f.readlines()

Just use 只需使用

strings = strings.splitlines()

instead of 代替

strings = strings.split()

splitlines method splits a string by newline characters splitlines方法用换行符分割字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM