How to rename an encrypted file without an ASCII character in ASCII

I have a file name "abc 枚 .xlsx" containing a non-ASCII character encoding, and I would like to delete all characters without ASCII characters to rename them to "abc.xlsx".

Here is what I tried:

import os import string os.chdir(src_dir) #src_dir is a path to my directory that contains the odd file for file_name in os.listdir(): new_file_name = ''.join(c for c in file_name if c in string.printable) os.rename(file_name, new_file_name) 

The following error occurs when os.rename() :

 builtins.WindowsError: (2, 'The system cannot find the file specified') 

This is on a windows system, sys.getfilesystemencoding() gives me mbcs if that helps anyone.

What should I do to get around this error and let me change the file name?

+4
source share
1 answer

Here you go, this also works with python 2.7

 import os import string for file_name in os.listdir(src_dir): new_file_name = ''.join(c for c in file_name if c in string.printable) os.rename(os.path.join(src_dir,file_name), os.path.join(src_dir, new_file_name)) 

Hooray! Remember to vote if you find this answer helpful !;)

+6
source

Source: https://habr.com/ru/post/1493537/


All Articles