0

The following code gives an error in python 3.8, with networkx, unicodecsv

with open('hero-network.csv', 'r') as data:
    reader = csv.reader(data)
    **for row in reader:**
        graph.add_edge(*row)
AttributeError: 'str' object has no attribute 'decode'
SMortezaSA
  • 589
  • 2
  • 15
  • 1
    It's not clear what is throwing this error. Can you include the entire stack trace, as well as what `graph` is? – C.Nivs Apr 17 '20 at 20:23
  • 4
    What happens if you use the regular Python `csv` module instead of `unicodecsv`? Bear in mind that `unicodecsv` was designed to get around shortcomings in Python *2.7*, but that error message looks like it's from Python *3*. – jjramsey Apr 17 '20 at 20:25
  • @jjramsey It is working with regular csv module. Thanks. – Muhammad Anas Raza Apr 17 '20 at 21:08

3 Answers3

2

unicodescv.reader expects a file opened in binary mode, because, in theory at least, it is going to work out how to decode the bytes.

with open('hero-network.csv', 'rb') as data:   # the mode is 'rb', not 'r'
    reader = csv.reader(data)
    for row in reader:
        graph.add_edge(*row)

As pointed out in the comments by jramsey, unicodecsv is more useful for Python2, when the standard library's csv module's unicode handling was poor. In Python 3 you can specify an encoding when you open the file and pass the resulting file object to the standard library's csv module.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
0

reader method in csv accept a reader not a str.

Check this post.

SMortezaSA
  • 589
  • 2
  • 15
0

That error happens when you try to decode a str that is already decoded. Are you passing the parameters correctly?

Source: 'str' object has no attribute 'decode'. Python 3 error?

Cblopez
  • 446
  • 2
  • 12