简体   繁体   中英

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?

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.

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()

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM