0101amt
0101amt

Reputation: 2488

How can I use readline method?

I have this trivial code:

from sys import argv

script, input_file = argv

def fma(f):
    f.readline()

current_file = open(input_file)

fma(current_file)

The contents of the txt file is:

Hello this is a test.\n
I like cheese and macaroni.\n
I love to drink juice.\n
\n
\n

I put the \n chars so you know I hit enter in my text editor.

What I want to accomplish is to get back every single line and every \n character.

The problem is, when running the script I get nothing back. What am I doing wrong and how can I fix it in order to run as I stated above?

Upvotes: 1

Views: 3103

Answers (5)

Morlock
Morlock

Reputation: 7131

the script should be as follow:

from sys import argv
script, input_file = argv

def fma(f):
    line = f.readline()
    return line

current_file = open(input_file)
print fma(current_file)

Upvotes: 1

michaelfilms
michaelfilms

Reputation: 724

Pretty certain what you actually want is f.readlines, not f.readline.

# module start
from __future__ import with_statement # for python 2.5 and earlier

def readfile(path):
    with open(path) as src:
        return src.readlines()

if __name__ == '__main__':
    import sys
    print readfile(sys.argv[1])
# module end

Note that I am using the with context manager to open your file more efficiently (it does the job of closing the file for you). In Python 2.6 and later you don't need the fancy import statement at the top to use it, but I have a habit of including it for anyone still using older Python.

Upvotes: 1

RanRag
RanRag

Reputation: 49587

Your function is not returning anything.

def fma(f):
    data = f.readline()
    return data

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

Upvotes: 1

yurib
yurib

Reputation: 8147

def fma(f):
    f.readline()

f.readline() is a function, it returns a value which is in this case a line from the file, you need to "do" something with that value like:

def fma(f):
    print f.readline()

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375942

Your function reads a line, but does nothing with it:

def fma(f):
    f.readline()

You'd need to return the string that f.readline() gives you. Keep in mind, in the interactive prompt, the last value produced is printed automatically, but that isn't how Python code in a .py file works.

Upvotes: 2

Related Questions