Skip to content Skip to sidebar Skip to footer

Error While Using '.readlines()' Function

The goal was to import the infile, read it, and print only two lines into the outfile.This is the code I had in IDLE: def main(): infile = open('names.py', 'r') outfile = o

Solution 1:

The error is because names.py is a string, and not a file object. The following code should work for you:

def main():
    infile = open('names.py', "r")
    outfile = open('orgnames.py', "w")

    # Prints the first two lines in outfile
    for line in infile.readlines()[:2]:
        outfile.write(line)

    infile.close()
    outfile.close()

main() 

Post a Comment for "Error While Using '.readlines()' Function"