Search code examples
pythonreadfile

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

Solution

  • readlines splits the entire file into lines and is nearly equivalent to file.read().split('\n'), except that the latter will remove new lines, whereas readlines by itself will retain new lines.

    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.