Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am facing a problem with the variable in python inside the for, for some reason is not "refreshing" values, I am trying to get the name of some the documents that I have in the Documents folder, but I have to remove the first and last element, now the documents name look like this:

151-document-name-5825

So I created the script to rename them to document-name but a variable that stores new name is not saving the update name, not sure where I am going wrong, Any help is appreciated. This is my code:

from pyunpack import Archive

import os

arr = os.listdir()

name = ""

ext = ""

elements = ""

direc = "C:\\Users\\kamr\\Desktop\\Organizar\\"

for i in arr:

  if i.endswith('.pdf'):

    elements = i.split('-')

    numb = len(elements) - 1

    coun = 0

    print(numb)

    name = ""

    for tex in elements:

      if coun > 0 and coun < numb:

        if coun + 1 == numb:

          print(tex)

          name = name + tex

        else:

          print(tex)

          name = name + tex + "-"

    print(name)

    #os.rename(direc + i, direc + name + ".pdf")

The "name" variable is always in blank

1 Answer

0 votes
by (36.8k points)
edited by

You never incremented your coun variable, it stays 0.

So this expression of if coun > 0 ... never executes, that is the reason the name variable is blank.

Lear data science with python course to improve technical knowledge.

Related questions

Browse Categories

...