On 08/14/2017 09:18 AM, banda gunda wrote: > Dear Tutor, > > > I have made some progress! > > But not yet got the results. > > Attached is revised code. > > > Specifically, the problem in below: > > > for root, dirs, files in os.walk(".", topdown=False): > for name in files: > print(os.path.join(root, name)) > os.rename(path + name, path + name.replace("---", "changed")) > #os.rename(path + "\\"+ name, path + "\\"+ name.replace("---", > "changed") > files[name] = os.sep.join([dirpath, name]) > > print (files) > > for name in dirs: > print(os.path.join(root, name)) > > > .\---DAT1\---DAT3\---000010.txt > > > --------------------------------------------------------------------------- > FileNotFoundError Traceback (most recent call last) > <ipython-input-6-316f0c967a9b> in <module>() > 2 for name in files: > 3 print(os.path.join(root, name)) > ----> 4 os.rename(path + name, path + name.replace("---", "changed")) > 5 #os.rename(path + "\\"+ name, path + "\\"+ > name.replace("---", "changed") > 6 files[name] = os.sep.join([dirpath, name]) > > FileNotFoundError: [WinError 2] The system cannot find the file specified: > 'E://---000010.txt' -> 'E://changed000010.txt'
Well, here are a few thoughts. (1) it will really help if your debugging print in line 3 makes the same path calculation as the command in line 4. You can see these don't match, which is a good hint you're getting something you don't expect. (2) where are you getting "path" from? It doesn't show in your code. Is there any reason why you don't just use the same calculation as in line 3? (3) for cautious programming, you can check if the file you are going to rename exists (os.path.exists() or os.path.isfile()) before trying to rename it, that would at least cause you not to take an exception and quit when you get something wrong. (4) you've still not fixed "dirpath" in line 6. Note the python documentation for the walk() function shows dirpath as the first element of the result triple, but you've called it "root" in your code, so this is probably what you meant. (5) why are you printing the whole list of files in line 7? That means you will show the files list each time you iterate through the list. (6) it's usually not a great idea to modify an interable while you're iterating over it (line 6). (7) you indicate you want to rename the directories as well, but you are not doing that. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor