readlines() 和 split() 之间的区别 [python]
difference between readlines() and split() [python]
假设我们有一个 file = open("filetext.txt", 'r')
split()方法和readlines()方法有什么区别
似乎都拆分了每一行并将其作为字符串放在列表中。
那么是什么让他们与众不同?
for line in file:
values = line.split() #break each line into a list
file.readlines() #return a list of strings each represent a single line in the file
这是主要区别:
A file
object has readlines
但不是 split
:
>>> print hasattr(file, 'split')
False
>>> print hasattr(file, 'readlines')
True
A str
object has split
但不是 readlines
:
>>> hasattr("somestring", 'split')
True
>>> hasattr("somestring", 'readlines')
False
为了回答你的问题,一个是对字符串对象进行操作,一个是对文件对象进行操作。
他们不做同样的事情,因为一个 returns 操作文件时的行列表和一个 returns 操作字符串时的分割线。
readlines
将整个文件分成几行,相当于 file.read().split('\n')
,但效率更高一些。你的榜样,
for line in file:
values = line.split()
按空格拆分每一行,构建该行中的单词列表。 value
在每次迭代时都会被覆盖,因此除非您将值保存在某处,否则一次只有部分文件在内存中。
readlines
进行与平台无关的行拆分,split
进行通用拆分。
举个例子:
In [1]: from StringIO import StringIO
In [2]: StringIO('test:test:test').readlines()
Out[2]: ['test:test:test']
In [3]: StringIO('test:test:test').read().split(':')
Out[3]: ['test', 'test', 'test']
假设我们有一个 file = open("filetext.txt", 'r')
split()方法和readlines()方法有什么区别 似乎都拆分了每一行并将其作为字符串放在列表中。 那么是什么让他们与众不同?
for line in file:
values = line.split() #break each line into a list
file.readlines() #return a list of strings each represent a single line in the file
这是主要区别:
A file
object has readlines
但不是 split
:
>>> print hasattr(file, 'split')
False
>>> print hasattr(file, 'readlines')
True
A str
object has split
但不是 readlines
:
>>> hasattr("somestring", 'split')
True
>>> hasattr("somestring", 'readlines')
False
为了回答你的问题,一个是对字符串对象进行操作,一个是对文件对象进行操作。
他们不做同样的事情,因为一个 returns 操作文件时的行列表和一个 returns 操作字符串时的分割线。
readlines
将整个文件分成几行,相当于 file.read().split('\n')
,但效率更高一些。你的榜样,
for line in file:
values = line.split()
按空格拆分每一行,构建该行中的单词列表。 value
在每次迭代时都会被覆盖,因此除非您将值保存在某处,否则一次只有部分文件在内存中。
readlines
进行与平台无关的行拆分,split
进行通用拆分。
举个例子:
In [1]: from StringIO import StringIO
In [2]: StringIO('test:test:test').readlines()
Out[2]: ['test:test:test']
In [3]: StringIO('test:test:test').read().split(':')
Out[3]: ['test', 'test', 'test']