使用 Python 使用 Counter 重命名

时间:2021-02-23 23:59:22

标签: python

我想提一下,几乎所有这些答案都可以很好地控制重命名的内容,我想检查所有有效的答案,只有一个答案无效,但是如果这对任何人有帮助,他们就会有4 个答案中有 3 个有效

我的共享脚本运行良好,但它重命名了它在目录中找到的所有内容,因此在使用我的共享脚本时请小心
对于超大文件,我使用这个 python

import os
# Function to rename multiple files
def main():
   i = 1000
   path="C:/Users/user/Desktop/My Folder/New folder/New folder/"
   for filename in os.listdir(path):
      my_dest ="(" + str(i) + ")" + ".txt"
      my_source =path + filename
      my_dest =path + my_dest
      # rename() function will
      # rename all the files
      os.rename(my_source, my_dest)
      i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

好的,所以我试图控制计数器只看到 txt 文件,如果我有 .txt、.jpeg、.mpeg、
一切都被重命名了,我怎么能控制这个只有 .txt 文件

还有一个问题,当我使用这个 Python 计数器或批处理计数器时,它会翻转我的文件名

示例

File_2019.txt - this should be renamed to (1000).txt
FileRecycled_2019.txt - this should be renamed to (1001).txt

结果

FileRecycled_2019.txt - this should be renamed to (1000).txt
File_2019.txt - this should be renamed to (1001).txt

根据文件名使用此方法时,它会翻转我的文件顺序
它不按字母顺序取它

我正在研究一个解决方案,一旦我找到它就会被翻转,如果它对其他人有帮助,我会分享它

好的,所以我有一个下划线卸妆批处理文件,并且修复了翻转
并正确重命名
对于较小的文件,我将使用这个

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=_"
Set "Replace= "

For %%a in (*.txt) Do (
    Set "File=%%~a"
    Ren "%%a" "!File:%Pattern%=%Replace%!"
)

set count=1000
for %%f in (*.txt) do (
  set /a count+=1
  ren "%%f" "(!count!).txt"
)

4 个答案:

答案 0 :(得分:1)

您可以在重命名之前检查文件名是否包含 .txt。

if filename.endswith(".txt"):
    os.rename(my_source, my_dest)
    i += 1

在文件名上,您没有指定名称的顺序。您可以使用 for filename in sorted(os.listdir(path)): 按字母顺序浏览。

我的解决方案是:

import os
import glob

def main():
    path = "C:/Users/user/Desktop/My Folder/New folder/New folder/"
    suffix = '.txt'
    files = glob.glob(path + '*' + suffix)
    for idx, filename in enumerate(sorted(files)):
        os.rename(
            filename,
            os.path.join(path, f"({1000 + idx})" + suffix)
        )

if __name__=="__main__":
    main()

这使用 glob 获取文件夹中带有 .txt 后缀的所有文件路径。它还使用 enumerate 来计算每个文件,而不必自己计算 i 值。文件名是使用 f-string 生成的。

答案 1 :(得分:1)

您可以使用 pathlib 模块完成此操作

from pathlib import Path
from os import chdir
path = Path.home() / 'desktop' / 'My Folder' / 'New folder' / 'New folder'  # The path to use
to_usenum = 1000  # Start num
alltxt = list(path.glob('*.txt'))  # Getting all the txt files
chdir(path)  # Changing the cwd to the path

for i, txtfile in enumerate(alltxt):
    to_usename = f"({to_usenum+i}).txt"  # The name to use
    txtfile.rename(to_usename) 

pathlib 模块在处理文件时会派上用场。代码中使用了 os 模块将当前工作目录更改为 path 的位置,因为重命名的文件将放置在当前工作目录中。

答案 2 :(得分:1)

我用简单的方法解决了:

import os
# Function to rename multiple files
def main():
   i = 1000
   path = 'C:/Users/user/Desktop/My Folder/New folder/New folder/'
   for filename in os.listdir(path):
      my_dest = f'({str(i)}).txt'
      my_dest = path + my_dest
      my_source = path + filename
      ext = my_source.split('.')[-1]
      if ext == 'txt':
          os.rename(my_source, my_dest)
          i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

答案 3 :(得分:0)

我的建议是使用 glob,试一试

import os
import glob
# Function to rename multiple files
def main():
    i = 1000
    path="C:/Users/user/Desktop/My Folder/New folder/New folder/"
    files = glob.glob(path + '*.txt')
    for filename in files:
        my_dest ="(" + str(i) + ")" + ".txt"
        my_source =path + filename
        my_dest =path + my_dest
        # rename() function will
        # rename all the files
        os.rename(my_source, my_dest)
        i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

这将搜索任何以 txt 扩展名结尾的文件名