user11553248
user11553248

Reputation:

Getting AttributeError: 'str' object has no attribute 'readlines' when trying to call method

So, I am trying to read only one line from a text file that I opened, but I keep getting this error: AttributeError: 'str' object has no attribute 'readlines'.

Here is the code. I am not very comfortable in python. What should I do?

file = askopenfilename(filetypes = (("Text File", ".txt"), ("All Files", ".")),
                       title = "Please, choose a file") 
if file is None:
    return

content = file.readlines()
print(content[74])

Upvotes: 0

Views: 1010

Answers (4)

RajeshM
RajeshM

Reputation: 862

Use askopenfile() instead.

file = askopenfile(filetypes = (("Text File", ".txt"), ("All Files", ".")), title="Please, choose a file", mode="r")
if file is None:
    return

Upvotes: 1

user11553248
user11553248

Reputation:

Thx for the answers, my question wasnt very clear sorry.

I made a button that allows to import a txt file. After reading this txt file I just want to retrieve a particular line

heres the few code i wrote.

        file = askopenfilename(filetypes = (("Text File", ".txt"), ("All Files", ".")),title = "Please, choose a file") 
      
        if file is None:
                return

        with open(file, 'r') as f_in:
                text = f_in.read()
    
        ```

Upvotes: 0

user16049466
user16049466

Reputation:

Try this

filename = askopenfilename(filetypes = (("Text File", ".txt"), ("All Files", ".")),title = "Please, choose a file") 
filename
f=open(filename)
f.read()
f.close()

Upvotes: 0

Aphrim
Aphrim

Reputation: 176

I am assuming that 'file' is just the path to the file, so you actually have to do like fileContent = open(file) and then fileContent.readlines(). I may be wrong though.

Upvotes: 0

Related Questions