如何从文件路径中删除多个单引号"/"?
2024-07-28
36
我的目标是在windows系统中删除目录中所有文件路径中的所有单引号。
例如
import os import re directory = "/home/oem/Documents/test"
以下不起作用。 它删除包含撇号的整个文件。 也无法删除订单并替换“'”
def remove_non_ascii_1(text): return ''.join(i for i in text if ord(i) == 39) [os.rename(os.path.join(dp, f), remove_non_ascii_1(os.path.join(dp, f))) for dp, dn, filenames in os.walk(directory) for f in filenames]
当有一个撇号时,以下方法有效
(即名为crazy'yeah.doc的文件更改为crazyyeah.doc。
但当路径中有多个撇号时(即crazy'yeah'yeah.doc),以下方法不起作用 )
def remove_apstrophes(text): return re.sub(r"(^.*)(')(.*$)", r"\1\3", text) [os.rename(os.path.join(dp, f), remove_apstrophes(os.path.join(dp, f))) for dp, dn, filenames in os.walk(directory) for f in filenames]
除非您想强制执行正则表达式,
否则此代码可以实现您想要执行的操作:
def remove_apostrophes(text): return text.replace("'", "")更新于:3个月前
赞一波!
相关文章
文章评论
评论问答