Search code examples
pythonpython-2.7filereadline

Why doesn't readline() return original text?


I'm trying to read files and collect the data inside the files. I am looking inside my directory, moving towards the folder, and looking there.

I would like to read every line in the file.

I have read that my output looks like binary. I've tried looking around on stackoverflow. I have also made sure the file I am reading is a txt file.

import os

def ratio(filename):

    cwd = str(os.getcwd())    
    cwd = cwd[:-8]
    cwd = cwd + "Equities\\" + str(filename) + ".txt"
    file = open(cwd, "r")
    line_1=str(file.readline(4))
    print(line_1)

The readline(4) should return:

Current assets

My readline(4) function returns:

ÿþA\000


Solution

  • If you are trying to read a specific line try:

    lines=file.readlines()
    text = lines[4]
    

    readline reads one line at a time. You can use readlines instead to read all the lines at once into a list.

    As I mentioned in my comment readline(4) only reads 4 bytes from the first line, not the fourth line.