使用'< file> .readlines()'函数时出错 [英] Error while using '<file>.readlines()' function

查看:178
本文介绍了使用'< file> .readlines()'函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是导入infile,对其进行读取,然后仅将两行打印到outfile中.这是我在IDLE中的代码:

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'

我以前在类似的情况下使用过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.

推荐答案

该错误是因为names.py是字符串,而不是文件对象.以下代码将为您工作:

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

这篇关于使用'&lt; file&gt; .readlines()'函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆