Domanda

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 = open('orgnames.py', "w")
    for i in range (2):
        line = ("names.py".readlines())
        print (line[:-1], infile = outfile)
    infile.close()
    outfile.close()
main() 

This is the error message I keep getting:

Traceback (most recent call last):
 File "C:/Python33/studentnames6.py", line 11, in <module>
  main()
 File "C:/Python33/studentnames6.py", line 6, in main
  line = ("names.py".readlines())
AttributeError: 'str' object has no attribute 'readlines'

I have used the function readlines in a similar situation before and it had worked fine. I don't understand why it's having an error now, or how to fix it.

È stato utile?

Soluzione

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() 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top