Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

imagine we have a 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 string in a list. so what makes them different ?

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
like image 422
Mozein Avatar asked Feb 24 '15 16:02

Mozein


People also ask

What does split () do in Python?

Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

What is the difference between readline () and Readlines () in Python?

Python readline() method will return a line from the file when called. readlines() method will return all the lines in a file in the format of a list where each element is a line in the file.

What is the difference between the read () and Readlines () methods?

While Read() and ReadLine() both are the Console Class methods. The only difference between the Read() and ReadLine() is that Console. Read is used to read only single character from the standard output device, while Console. ReadLine is used to read a line or string from the standard output device.

What is Readlines () in Python?

The readlines() method returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned. If the total number of bytes returned exceeds the specified number, no more lines are returned.


1 Answers

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

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

splits each line by its spaces, building a list of words in the line. value is overwritten on each iteration so unless you save values somewhere, only parts of the file are in-memory at a single time.

like image 174
tdelaney Avatar answered Nov 01 '22 02:11

tdelaney