Error while using '<file>.readlines()' function

荒凉一梦 提交于 2019-12-12 05:56:14

问题


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.


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


来源:https://stackoverflow.com/questions/21544486/error-while-using-file-readlines-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!