使用'<file> .readlines()'函数</file>时出错

时间:2014-02-04 05:17:50

标签: python file-processing

目标是导入infile,读取它,并在outfile中只打印两行。这是我在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() 

这是我不断收到的错误消息:

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'

我之前在类似的情况下使用过函数readlines,它运行良好。我不明白为什么现在有错误,或者如何解决它。

1 个答案:

答案 0 :(得分:2)

错误是因为names.py是一个字符串,而不是文件对象。以下代码适合您:

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