【问题标题】:How to create a folder the name of multiple files, to move files into that folder, and then rename all of those files如何以多个文件的名称创建文件夹,将文件移动到该文件夹​​中,然后重命名所有这些文件
【发布时间】:2021-04-25 19:33:46
【问题描述】:

我正在使用网络爬虫来爬取一个包含大量 html 文件的相当大的网站,它所做的是将文件保存为(页面名称)。

我希望将文件保存为(页面名称的文件夹)/index.html,因为它是在原始网站上设置的。

爬虫甚至没有将它们保存为(页面名称).html,它们没有文件扩展名。

我已经在 2 天内抓取了该网站的大部分内容,所以我不想重新抓取它。

有谁知道我如何为每个文件创建一个文件夹名称,但只有那些没有文件扩展名的文件,因为有些 jsons 和 swfs 不应该有一个文件夹。

然后将这些文件移动到具有其名称的文件夹中,

然后将所有文件重命名为 index.html?

是否可以使用 cmd 命令(我猜是 3 个)

我试过了

from glob import glob
from os import mkdir
from os.path import join
from shutil import move

files = glob('*')
for file in files:
    if not '.' in file:
        move(file, file+'_tmp')
        mkdir(file)
        move(file+'_tmp', join(file, 'index.html'))

在python中和

for %i in (*) do mkdir "%~ni"
for %i in (*) do move "%i" "%~ni"

在cmd中

Python 给出了语法错误,而 cmd 为每个文件创建了一个文件夹,而不仅仅是没有扩展名的文件,破坏了其他文件,而且我找不到如何自动重命名它们。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • this in python from glob import glob from os import mkdir from os.path import join from shutil import move files = glob('*') for file in files: if not '.'在文件中:move(file, file+'_tmp') mkdir(file) move(file+'_tmp', join(file, 'index.html'))
  • 请不要在评论中添加代码,因为它变得不可读。编辑您的问题并将代码作为格式化文本插入其中。
  • 我现在已经编辑了帖子。

标签: windows powershell batch-file cmd


【解决方案1】:

for %i in (*) do... 将通配符 * 解释为“所有文件”。包括点以确保只处理没有扩展名的文件:

在命令行上:

for %a in (*.) do @(ren "%a" "%~na.tmp" && md "%~na" & move "%a.tmp" "%~na\index.html")`

作为批处理文件:

for %%a in (*.) do (
  ren "%%a" "%%~na.tmp"
  md "%%~na"
  move "%%a.tmp" "%%~na\index.html"
)

【讨论】:

  • 如果文件没有扩展名,可以创建同名目录吗?
  • @lit:不,它不能...:/。感谢您的提示,已编辑答案。
最近更新 更多