1

Im having trouble printing the return value of one of my functions

def readfile(filename):
    '''
    Reads the entire contents of a file into a single string using
    the read() method.

    Parameter: the name of the file to read (as a string)
    Returns: the text in the file as a large, possibly multi-line, string
    '''
    try:
        infile = open(filename, "r") # open file for reading

        # Use Python's file read function to read the file contents
        filetext = infile.read()

        infile.close() # close the file

        return filetext # the text of the file, as a single string
    except IOError:
        ()


def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    readfile(file)

How do I save readfile's value into a different variable then print the value of the variable where you saved readfile's return value?

4 Answers 4

2

This is the simplest way, I wont recommend adding a try block in the function because you will have to use it anyways after or return a empty value which is a bad thing

def readFile(FileName):
    return open(FileName).read()

def main():
    try:
        File_String = readFile(raw_input("File name: "))
        print File_String
    except IOError:
        print("File not found.")

if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried:

def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    read_contents = readfile(file)
    print read_contents

Comments

0
def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    text = readfile(file)

    print text

Comments

0

this should do it, just assign the functions call to a variable.

But in case when the exception is raised you're returning nothing, so the function will return None.

def main():
    ''' Read and print a file's contents. '''
    file = input('Name of file? ')           #no need of str() here
    foo=readfile(file)
    print foo

and use with statement when handling files, it takes care of the closing of the file:

def readfile(filename):
     try:
        with open(filename) as infile :
           filetext = infile.read()
           return filetext    
     except IOError:
        pass 
        #return something here too

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.