[Tutor] File renaming using os.rename problem

Dave Angel davea at ieee.org
Tue Dec 8 21:47:02 CET 2009


spir wrote:
> Roy Hinkelman <royhink at gmail.com> dixit:
>
>   
>> I can't find anything on this error I am getting when renaming some files.
>> I'm pulling info from a csv file and parsing it to build new file names.
>>
>> Any pointers appreciated
>>
>> Roy
>>
>> My code:
>> # RENAME FILES using META file - new name = [place]_[state]_[sku].tif
>>
>> import re, os, csv
>>
>> # DEFINE
>> _meta_file = "C:\\Documents and Settings\\rhinkelman\\My Documents\\My
>> Dropbox\\Public\\Python code examples\\topo_meta_TEST.csv"
>> _files_to_mod = "\\\\Dc2\\inetpub2\\Image Production\\missing_topo\\topo
>> sz3\\test"
>> _del_space = re.compile( ' ' )
>>
>> #OPEN file containing TOPO meta, DEFINE OLD AND NEW NAMES
>> _meta = csv.reader(open(_meta_file, "r"))
>> for _row in _meta:
>>     if _row[0] == "NAME":
>>         continue
>>     print '|'.join(_row) # test
>>     old_name = _row[4].lstrip('o') + ".pdf"
>>     new_name = _row[0] + "_" + _row[1] + "_" + _row[4] + ".pdf"
>>     new_name = _del_space.sub( '_', new_name )
>>     print old_name + " - " + new_name # test
>>
>> # OPEN DIR OF FILES TO BE RENAMED AND LOOK FOR NAME, RENAME AND CONTINUE
>>     for fname in os.listdir(_files_to_mod):
>>         if fname == old_name:
>>             print fname # test
>>             os.rename(fname, new_name)
>>             break
>>         else:
>>             continue
>>
>>
>> AND the error
>>     
>> Aberdeen|CA|36.875|-118.250|o36118h3
>> 36118h3.pdf - Aberdeen_CA_o36118h3.pdf
>> 36118h3.pdf
>> Traceback (most recent call last):
>>   File "C:\Documents and Settings\rhinkelman\My Documents\My
>> Dropbox\Public\Python code examples\Rename_topo_files.py", line 25, in
>> <module>
>>     os.rename(fname, new_name)
>> WindowsError: [Error 2] The system cannot find the file specified
>>     
>
> Why don't you simply print out fname? This should point you to the error.
>
> Denis
> ________________________________
>
> la vita e estrany
>
> http://spir.wikidot.com/
>
>   
Actually he did, in the line immediately before the os.rename() call.  
See the line just before the traceback  36118h3.pdf

Roy, your problem is that you've confirmed that the file  36118h3.pdf 
exists in the "test" directory (specified in _files_to_mod), but you're 
trying to rename a different file in the current directory.

Your call to os.rename() needs to have a full path to the actual file.  
See os.path.join() to build such.

DaveA



More information about the Tutor mailing list