Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python从.jpg文件中删除随机生成的文件扩展名_Python_Regex_Bash_Scripting_Batch Rename - Fatal编程技术网

使用python从.jpg文件中删除随机生成的文件扩展名

使用python从.jpg文件中删除随机生成的文件扩展名,python,regex,bash,scripting,batch-rename,Python,Regex,Bash,Scripting,Batch Rename,我最近恢复了一个意外删除的文件夹。它有.jpg和.tar.gz文件。但是,所有文件现在都附加了某种哈希扩展名,每个文件的扩展名都不同。文件夹中有600多个文件。因此,示例名称如下: IMG001.jpg.3454637876876978068 IMG002.jpg.2345447786787689769 IMG003.jpg.3454356457657757876 及 我希望有一个脚本可以依次执行(也许我可以指定扩展名,或者它可以有两次迭代,一次通过.jpg文件,另一次通过.tar.gz),并

我最近恢复了一个意外删除的文件夹。它有.jpg和.tar.gz文件。但是,所有文件现在都附加了某种哈希扩展名,每个文件的扩展名都不同。文件夹中有600多个文件。因此,示例名称如下:

IMG001.jpg.3454637876876978068
IMG002.jpg.2345447786787689769
IMG003.jpg.3454356457657757876

我希望有一个脚本可以依次执行(也许我可以指定扩展名,或者它可以有两次迭代,一次通过.jpg文件,另一次通过.tar.gz),并从开始清理文件名的最后一部分。就在号码前面。因此,最终的文件名将以.jpg和.tar.gz结尾

到目前为止,我对python的了解是:

import os

def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            os.path.splitext(currentFile)

scandirs('C:\Users\ad\pics')
很明显,它不起作用。我将感谢任何帮助。我也会考虑使用BASH脚本,但是我不知道怎么做。< > P> <代码> SUUTIL。 至少我认为…

shutil.move(currentFile,os.path.splitext(currentFile)[0])


至少我认为…

下面是我将如何使用正则表达式来实现它:

import os
import re

pattern = re.compile(r'^(.*)\.\d+$')


def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            match = pattern.match(currentFile)
            if match:
                os.rename(
                    os.path.join(root, currentFile),
                    os.path.join(root, match.groups(1)[0])
                )

scandirs('C:/Users/ad/pics')

下面是我将如何使用正则表达式执行此操作:

import os
import re

pattern = re.compile(r'^(.*)\.\d+$')


def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            match = pattern.match(currentFile)
            if match:
                os.rename(
                    os.path.join(root, currentFile),
                    os.path.join(root, match.groups(1)[0])
                )

scandirs('C:/Users/ad/pics')
由于您标记为,我将给您一个答案,该答案将删除目录中所有文件/目录的最后一个扩展名:

for f in *; do
  mv "$f" "${f%.*}"
done
由于您标记为,我将给您一个答案,该答案将删除目录中所有文件/目录的最后一个扩展名:

for f in *; do
  mv "$f" "${f%.*}"
done

你好像在窗户上;我怀疑您是否需要bash脚本来处理此问题;我怀疑您是否需要bash脚本来处理此问题。我是否要在当前目录下运行此脚本?@TendekaiMuchenje Yes我是否要在当前目录下运行此脚本?@TendekaiMuchenje Yes