0

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])
2
  • 1
    But, surely askopenfilename() only returns a filename. Did you mean content = open(file).readlines()? Commented Jun 2, 2021 at 16:44
  • The attribute error means that readline() is not a string method which is because file is a string, not an open file. Commented Jun 2, 2021 at 16:57

4 Answers 4

1

Use askopenfile() instead.

file = askopenfile(filetypes = (("Text File", ".txt"), ("All Files", ".")), title="Please, choose a file", mode="r")
if file is None:
    return
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Try this

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.