[英]Error while using '<file>.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: 目标是导入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()
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. 我以前在类似的情况下使用过函数readlines,它运行良好。 I don't understand why it's having an error now, or how to fix it.
我不明白为什么它现在有错误,或者如何解决它。
The error is because names.py
is a string, and not a file object. 错误是因为
names.py
是一个字符串,而不是文件对象。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.