Python3 does not accept file.name

Asked

Viewed 35 times

1

I’m with a script where I want to take the name of each file along the first line within each file and pass those in a list within a txt.

#modifica titulos de arquivos
import os
import glob

s=("-")

arq=open("listapdf.txt","w")
for file in glob.glob('*.pdf'):
    f = str(file.name)
    fr = str(file.readline())
    arq.write(f+s+fr)
    arq.write("\n")
exception (RuntimeError, TypeError, NameError)
pass

in the output points to the following error:

 h1k3rpath@h1k3rpath-Ubuntu:~/Downloads/recovery/sabadoroadsec/pdf$
 python3 lista.py Traceback (most recent call last):   File "lista.py",
 line 9, in <module>
     f = str(file.name) AttributeError: 'str' object has no attribute 'name'

I’ve already altered and reread the call with str and without str

I tried to use keyword instead of naming variant, tried some other things, but still can’t get around this error.

I’m not using it properly file.name or there’s another way to do it?

1 answer

1

According to Python3 documentation (https://docs.python.org/3/library/glob.html) glob. returns a string list. Strings do not have the attribute .name.

This is the error of your code.

Instead of using

f = str(file.name)

Use only

f = file
  • and how to get the file name?

  • Since you are using glob.glob, the file name is the file variable of your loop for

  • I’ll test and I’ll be right back

  • same error now pointed p the file.readline(). how do I grab the first line of the file?

  • So... the file variable contains the file name. To read the file you need to open it. To do this, use the OPEN method, as you did with the Arq variable.

  • didn’t work out. if I leave inside the structure of the glob, it points to str problem, if I leave before the structure, ie outside the structure of the for, it points 'file is not defined'

  • #modifies filenames import os import glob s=("-") Arq=open("listapdf.txt","w") for file in glob.glob('*.pdf'): f = open(file) fr = str(file.readline()) Arq.(f+s+fr) Arq.(" n") Exception (Runtimeerror, Typeerror, Nameerror) pass

  • the same string error. I think agr would have to review the whole logic structure on account of glob, which I did not know of these glob attributes

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.