如何在多个文件中将某个标签中的字符串更改为小写

我有以下要求,我试图在 Windows 10 中使用 Python 脚本来满足:

  1. 递归地将多个文件夹中的所有文件名更改为小写。为此,我使用了以下代码:

    import os path = "C://Users//shilpa//Desktop//content"for dir,subdir,listfilename in os.walk(path): 
      for filename in listfilename:  
            new_filename = filename.lower()
            src = os.path.join(dir, filename) 
            dst = os.path.join(dir, new_filename) 
            os.rename(src,dst)
  2. 更新嵌入在特定标签中的这些文件的引用。这里的标签是 <img href=(filename.png)>。在这里,<img href=>是常量并且文件名 filename.png 是不同的。

所以,这里是一个例子:

现有文件名:

  • ABC.dita

  • XYZ.dita

  • IMG.PNG

这些在不同的文件中 IMG.PNG被引用,比如说在XYZ.dita.

在 step1 之后,这些更改如下:

  • abc.dita

  • xyz.dita

  • img.png

这将破坏不同文件中包含的所有引用。

我想更新所有更改的文件名引用,以便链接保持不变。

我对 Python 没有任何经验,而且只是初学者。为了实现第 2 步,我应该能够使用正则表达式并找到一个模式,比如说,

<img href="(this will be a link to the IMG.PNG>". 这将是.dita文件的一部分。

step1 之后,文件中的引用将中断。

如何更改文件名并保留其引用?这里的问题是,在所有文件中查找并用新名称替换旧名称。

任何帮助表示赞赏。


慕莱坞森
浏览 80回答 1
1回答

HUWWW

我假设您有一个包含所有相关文件的文件夹。所以问题分为两部分:在文件上循环运行对于每个文件,降低参考循环播放文件这可以使用glob或来完成os.walk。import osupper_directory = "[insert your directory]"for dirpath, directories, files in os.walk(upper_directory):&nbsp; &nbsp; for fname in files:&nbsp; &nbsp; &nbsp; &nbsp; path = os.path.join(dirpath, fname)&nbsp; &nbsp; &nbsp; &nbsp; lower_file_references(path)小写 参考文献当您拥有文件的路径时,您需要从中读取数据:with open(path) as f:&nbsp; &nbsp; s = f.read()获得引用文件的数据后,您可以使用此代码来降低引用字符串:head = "<img href="tail = ">"img_start = s.find(head, start)while img_start != -1:&nbsp; &nbsp; img_end = s.find(">", img_start)&nbsp; &nbsp; s = s[:img_start] +s[img_start:img_end].lower() + s[img_end:]&nbsp; &nbsp; img_start = img_end或者,您可以使用一些 XML 解析模块。例如 BeautifulSoup,这将有助于避免像href=vshref =from bs4 import BeautifulSoup as bss = bs(s)imgs = s.find_all("img")for i in imgs:&nbsp; &nbsp; if "href" in i.attrs:&nbsp; &nbsp; &nbsp; &nbsp; i.attrs["href"] = i.attrs["href"].lower()s = str(s)然后,您可以通过这两种方式重写文件。你可以这样做:with open(path, "w") as f:&nbsp; &nbsp; f.write(s)把它们放在一起import osfrom bs4 import BeautifulSoup as bsdef lower_file_references(file_path):&nbsp; &nbsp; with open(path) as f:&nbsp; &nbsp; &nbsp; &nbsp; s = f.read()&nbsp; &nbsp; s = bs(s)&nbsp; &nbsp; imgs = s.find_all("img")&nbsp; &nbsp; for i in imgs:&nbsp; &nbsp; &nbsp; &nbsp; if "href" in i.attrs:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i.attrs["href"] = i.attrs["href"].lower()&nbsp; &nbsp; s = str(s)&nbsp; &nbsp; with open(path, "w") as f:&nbsp; &nbsp; &nbsp; &nbsp; f.write(s)upper_directory = "[insert your directory]"for dirpath, directories, files in os.walk(upper_directory):&nbsp; &nbsp; for fname in files:&nbsp; &nbsp; &nbsp; &nbsp; path = os.path.join(dirpath, fname)&nbsp; &nbsp; &nbsp; &nbsp; lower_file_references(path)我必须说这是一个简单的方法,假设你的文件不是很大,它会很好用。如果您有无法一次全部读取到内存的大文件,或者有很多文件,您可能需要考虑避免读取所有文件数据的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python