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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With