anon
anon

Reputation:

Why do I get this error in this Python code?

I am trying to extract the first words in a file by Python.

My code

import re

con1 = pg.DB('tk', 'localhost', 5432, None, None, 'masi', '123')                
f1="/home/masi/fy.txt"

print re.findall(r"\w+", f1.read())

I get the error

Traceback (most recent call last):                                              
  File "<stdin>", line 7, in <module>
AttributeError: 'str' object has no attribute 'read'

Upvotes: 0

Views: 230

Answers (3)

inspectorG4dget
inspectorG4dget

Reputation: 113905

When you assign f1 to the filepath, you are actually saying the f1 is the string referring to the filepath. Instead, if you were to assign it to the return value of the 'open' method called on that filepath (as Jonathan suggests), then f1 would be an open file.

Upvotes: 0

Jonathan
Jonathan

Reputation: 1731

I don't know Python but it looks like you need to open the file which is

f=open('/tmp/workfile', 'r')

According to this site

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 837886

f1.read() should be open(f1).read()

Upvotes: 5

Related Questions