简体   繁体   中英

python replace special character

I want to copy the file to a new place in windows7 64bit. But I found some special characters in the file name can cause error 22 when using shutil.copy2 (but this file is legal in windows GUI and can be copied with a mouse). I believe the error22 means the source file can't be found by citing this file name. So my workaround would be to remove or replace the special characters in any file name which causes this problem in windows7 64bit. In general user keep copying files from other folders to this folder so the file name must be handled by some varables rather than constants. But as an example, I just put two files names in the example code. I put the code shown in the picture:

# -*- coding: gbk*-
#!/usr/bin/python
#Filename:ae.py
import os,shutil,time,re,string,sys  #re is regular expression
from nt import chdir
import win32api,win32file
import unicodedata,codecs
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf"
des="C:\\Users\\Administrator\\Desktop\\How-To Geek Forums.pdf"
#chdir(os.path.dirname(scr))
os.rename(scr,des)

and I got

WindowsError:[Error 123]

I think that means I can't even rename it using python script once there are some special characters like «

So, it looks like you are creating a regular expression to match the pattern of a filename, but you already know the name?

When you say special characters, are you speaking specifically about whitespace?

Here's your code for readability:

#!/usr/bin/python
#Filename:ae.py 
import os,shutil,time,re,string,sys 
#re is regular expression 
from nt import chdir import win32api,win32file 
import unicodedata,codecs 
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf" 
des="C:\Users\Administrator\Desktop\How-To Geek Forums.pdf" #
chdir(os.path.dirname(scr)) os.rename(scr,des)

check out http://docs.python.org/library/os.html#os.listdir

I would probably just get a list of files in the directory with

chdir(os.path.dirname(scr)
files = os.listdir(“.”)
for name in files:
    os.rename(name,des+”/“+name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM