Python Forum

Full Version: Invalid Syntax problem (?!?)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am just starting to learn Python with the Python 3.5.2 version. I am supposed to start with a really easy task, renaming all the files in a folder. (Taking out the numbers out of the filenames.)

But I always get a Syntax-Error message (Invalid Syntax). Can someone please help me? I don't know what is wrong!

line 13: os apparently is a syntax error
import os

def rename_files():
    #(1) get file names form a folder
    file_list = os.listdir(r"C:\Users\harley\Documents\Python\Introduction\rename")
    #print(file_list)
    saved_path = os.getcwd()
    print("Current Wokring Directory is", saved_path)
    os.chdir(r"C:\Users\harley\Documents\Python\Introduction\rename")
    #(2) for each file, rename filename
    for file_name in file_list:
        os.rename(file_name, filename.translate("0123456789")
    os.chdir(saved_path)

rename_files()
Show us the whole traceback, please.
You missed a close-paren on line 12.
Missing parenthese in line 12.
Like this.
os.rename(file_name, filename.translate("0123456789"))
Hello!
In Python 3 str.translate() works a bit different.
Python 3.5.2 (default, Sep 10 2016, 08:21:44) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: file_name = '0012ow32jioo123.hh1'

In [2]: table = {}

In [3]: for key in range(10):
   ...:     table[ord(str(key))] = None
   ...:     

In [4]: table
Out[4]: 
{48: None,
 49: None,
 50: None,
 51: None,
 52: None,
 53: None,
 54: None,
 55: None,
 56: None,
 57: None}

In [5]: new_file = file_name.translate(table)

In [6]: new_file
Out[6]: 'owjioo.hh'
I suppose you want to do this on the base name of the file not to an extension too. As you see is 'hh' now. This will ruin your mp3 collection  Smile