Difference between readlines () and split () [python]

imagine we have file = open("filetext.txt", 'r')

what is the difference between the split () method and the readlines () method It seems that both split each line and put it as a line in a list. so what sets them apart?

 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 
+5
source share
3 answers

readlines splits the entire file into lines and is equivalent to file.read().split('\n') , but a bit more efficient. Your example

 for line in file: values = line.split() 

breaks each line into its own spaces, building a list of words in a line. value overwritten at each iteration, so if you don't save the values โ€‹โ€‹somewhere, only parts of the file are in memory at a time.

+3
source

readlines is the division of the agnostic line of the platform, and split is the general splitting.

As an example:

 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'] 
+1
source

This is the main difference:

A file readlines object but not split :

 >>> print hasattr(file, 'split') False >>> print hasattr(file, 'readlines') True 

A str a split object but not readlines :

 >>> hasattr("somestring", 'split') True >>> hasattr("somestring", 'readlines') False 

And to answer your question, one works with a string object, and one works with a file object.

They do not do the same, since each returns a list of lines when working on a file, and one returns a dividing line when working with a line.

0
source

Source: https://habr.com/ru/post/1214093/


All Articles