使用Python在标题中使用引号重命名文件



我知道在此网站上已经问过几次类似的问题,但是提供的解决方案对我不起作用。

我需要重命名使用标题,例如

a.jpg
'b.jpg'
c.jpg
"d.jpg"

to

a.jpg
b.jpg
c.jpg
d.jpg

这些标题中的一些标题中也有引号,但无论是否被删除都没关系。

我尝试了

import os
import re
fnames = os.listdir('.')
for fname in fnames:
   os.rename(fname, re.sub("'", '', fname))

import os
for file in os.listdir("."):
  os.rename(file, file.replace("'", "")) 

当时也对"引号也可以做同样的事情,但是标题保持不变。我认为这可能是由于ListDir在其周围的引号返回文件名,但我不确定。

编辑:我正在使用Ubuntu 18.04。

在Windows上,其中包含双引号的文件名不是有效的文件名。但是,单引号的文件名有效。

python中的带有双引号的字符串看起来像:

'"I'm a string with a double quote on each side"'

python中的单个引号的字符串看起来像:

"'I'm a string with a single quote on each side'"

因为您不能在Windows上使用双引号文件名,所以您不能os.rename('"example.txt"', "example.txt")。因为甚至不可重命名。

您可以将此脚本放在桌面上,并在执行时观看文件名更改:

import os
open("'ex'am'ple.t'xt'",'w')
input("Press enter to rename.")
#example with single quotes all over the filename
os.rename("'ex'am'ple.t'xt'", "example.txt")
open("'example.txt'",'w')
input("Press enter to rename.")
#example with single quotes on each side of filename
os.rename("'example2.txt'", "example2.txt")

这是我尝试使用循环的尝试,就像您一样,并在字符串上使用的列表理解,这也是一个可观的。

import os
files = os.listdir(os.getcwd())
for file in files:
    new_name = ''.join([char for char in file if not char == '''])
    print(new_name)
    os.rename(file, new_name)

用字符编辑Forbidden_Chars列表,您将来不需要文件名。请记住,这也会更改文件夹名称afaik,因此您可能需要在循环的开始时检查 如果OS.Isfile(文件):在更改名称之前。实际上,我不明白您将如何使用文件名,其中包括引号内部的扩展名,但这无论哪种方式都可以。我强烈建议您要删除点。我还建议在使用其功能之前窥视OS模块的文档,因为它们可以做您可能不知道的事情。例如:重命名到目录中的现有文件名只是默默替换文件。

最新更新