开发者

What's wrong with this python code that should rename files?

this code is meant to ask for a directory, then list al files in that directory, then rename then to their position in that list, problem is I always get error 2, file not found, while if i print the list it apperently does find the files because the list is not blank.

import os, sys    
path = input("input path: ")    
dirs = os.listdir(path)    
for i in range(0,len(dirs)):    
    os.rename(dirs[开发者_Go百科i], str(i))

Given input files, I want to rename the base file name with a number, but preserving the file extension. Thus

Input 'a.txt', 'test.txt', 'test1.txt'

Output '0.txt', '1.txt', '2.txt'


Yup, so you do need to add the code from my comment. The problem is os.listdir is only returning base file names so when the rename is called, it expects to find those files in whatever directory Python thinks it should be in. By adding the os.path.join, it will build out the fully qualified path to the file so the rename will work correctly.

In the comments, OP stated the files got moved up a folder which lead me to believe the rename needed a fully qualified path on second argument. Also, we learned the files should not be renamed from foo.txt to 0 but instead should become 0.txt etc (preserving file extension) This code now

import os, sys
path = input("input path: ")
dirs = os.listdir(path)
for i in range(0,len(dirs)):
   # capture the fully qualified path for the original file
   original_file = os.path.join(path, dirs[i])
   # Build the new file name as number . file extension
   # if there is no . in the file name, this code goes boom
   new_file = os.path.join(path, str(i) + '.' + original_file.split('.')[-1])

   print "Renaming {0} as {1}".format(original_file, new_file)
   os.rename(original_file, new_file)

Verified with Python 2.6.1

Showing the relevant bits from the command line. You can see the empty files bar.txt and foo.txt are renamed to 0 and 1

>>> path = input("Input path")
Input path"/Users/bfellows2/so"
>>> dirs = os.listdir(path)
>>> dirs
['bar.txt', 'foo.txt']
>>> for i in range(0,len(dirs)): 
...  os.rename(os.path.join(path, dirs[i]), str(i))
... 
>>> 
[1]+  Stopped                 python
Helcaraxe:so bfellows2$ ls -al
total 0
drwxr-xr-x    4 bfellows2  bfellows2   136 Sep  3 20:30 .
drwxr-xr-x  100 bfellows2  bfellows2  3400 Sep  3 20:24 ..
-rw-r--r--    1 bfellows2  bfellows2     0 Sep  3 20:24 0
-rw-r--r--    1 bfellows2  bfellows2     0 Sep  3 20:24 1
Helcaraxe:so bfellows2$ python -V
Python 2.6.1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜