user20430376
user20430376

Reputation:

AttributeError: 'str' object has no attribute 'readline' when trying to get all lines from a file

trying to get all lines in a file and print them out

topic = 1
if topic == 1:
    allquestions = open("quizquestions1.txt","r")
    allquestions = allquestions.read()
    print(allquestions.readfile())

Upvotes: 1

Views: 45

Answers (2)

Amir reza Riahi
Amir reza Riahi

Reputation: 2460

The read method for a file will return the file content. You can use help function for it:

read(size=-1, /) method of _io.TextIOWrapper instance
    Read at most n characters from stream.
    
    Read from underlying buffer until we have n characters or we hit EOF.
    If n is negative or omitted, read until EOF.

It will return the content as a string containing whole file content.

topic = 1
if topic == 1:
    with open("quizquestions1.txt","r") as file:
        allquestions = file.read()
        print(allquestions)

You can also use readlines method to get a splitted content of file based on \n character.

Upvotes: 0

Bhargav
Bhargav

Reputation: 4118

It's only allquestions in print..You alredy read lines before no need to read again.

topic = 1
if topic == 1:
    allquestions = open("quizquestions1.txt","r")
    allquestions = allquestions.read()
    print(allquestions)

Upvotes: 1

Related Questions