简体   繁体   English

使用&#39;时出错 <file> .readlines()&#39;函数

[英]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.

相关问题 在使用 readlines 和 .split() 函数时,使用 for 循环进行迭代会更容易吗? - While using readlines and .split() function, would it be easier to iterate through with for-loop? 为什么在使用 readlines() 读取文件时出现 lis 索引超出范围错误? - why getting lis index out of range error while reading file with readlines()? 使用 readlines 解析文件并在 python 中拆分 function - Parsing a file with readlines and split function in python xlsx文件的Readlines功能不正确 - Readlines function for an xlsx file works inproper Python 读取行 function 未读取文件中的第一行 - Python readlines function not reading first line in file 如何在python中使用readlines读取文件时提取相同列表的不同索引 - How to extract different indexes of the identical lists while reading a file using readlines in python readlines函数应用于应用于作为网页响应的文件时抛出错误 - readlines function throwing an error when applied to a file obtained as a response from a webpage 使用和不使用 readlines() 方法打印文件的内容 - Printing contents of a file with and without using readlines() method 在 python 中使用 readlines() 读取日志文件 - read log file by using readlines() in python 从文件指针读取文件而不使用 readlines - read file from file pointer without using readlines
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM