【问题标题】:How to change multiple filenames in a directory using Python如何使用 Python 更改目录中的多个文件名
【发布时间】:2016-04-29 20:35:57
【问题描述】:

我正在学习 Python,我的任务是:

  • 在目录中每个名称的开头添加“file_”
  • 更改扩展名(目录当前包含 4 种不同的类型:.py、.TEXT、.rtf、.text)

我有很多文件,都有不同的名称,每个文件有 7 个字符长。我能够更改扩展名,但感觉非常笨拙。我很肯定有一种更简洁的方式来编写以下内容(但它的功能,所以没有抱怨):

    import os, sys
    path = 'C:/Users/dana/Desktop/text_files_2/'
        for filename in os.listdir(path):
            if filename.endswith('.rtf'):
                newname = filename.replace('.rtf', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.py'):
                newname = filename.replace('.py', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.TEXT'):
                newname = filename.replace('.TEXT', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.text'):
               newname = filename.replace('.text', '.txt')
               os.rename(filename, newname)

我还有一点问题:

  1. 脚本当前必须在我的目录中才能运行。
  2. 我不知道如何在每个文件名的开头添加“file_”[你会认为这很容易]。我尝试将 newname 声明为

    newname = 'file_' + str(filename)
    

    然后声明文件名未定义。

对于我现有的两个问题的任何帮助将不胜感激。

【问题讨论】:

  • newname = 'file_' + filename 应该可以工作。您不需要str(),因为filename 已经引用了一个字符串,但即使这样也应该有效。也许你在循环之外尝试过?
  • 你说得对,它在我的循环之外
  • 另一条评论:发布代码时请注意缩进。你知道它在 Python 中很关键。例如,显示的代码不会按原样编译。

标签: python file-handling


【解决方案1】:

使用os.path.join() 提供完整路径名:

os.rename(os.path.join(path, filename), os.path.join(name, newname))

你可以从任何目录运行你的程序。

您可以进一步简化您的程序:

extensions = ['.rtf', '.py', '.TEXT', '.text']
for extension in extensions:
     if filename.endswith(extension):
         newname = filename.replace(extension, '.txt')
         os.rename(os.path.join(path, filename), os.path.join(path, newname))
         break

不再需要所有其他 elif 语句。

【讨论】:

  • 试过了,然后名称未定义。
  • 声明这些扩展要简单得多。 -谢谢你的建议。
  • Traceback(最近一次调用最后):文件“C:/Users/dana/Desktop/scott_suffix_change2.py”,第 16 行,在 os.rename(os.path.join(path , 文件名), os.path.join(name, newname)) NameError: name 'name' is not defined
  • 对不起。错字。更新了我的答案。不是name,而是path
【解决方案2】:
import os, sys
path = 'data' // Initial path

def changeFileName( path, oldExtensions, newExtension ):
    for name in os.listdir(path):
        for oldExtension in oldExtensions:
            if name.endswith(oldExtension):
                name = os.path.join(path, name)
                newName = name.replace(oldExtension, newExtension)
                os.rename(name, newName)
                break;

if __name__ == "__main__":
    changeFileName( 'data', ['.py', '.rtf' , '.text', '.TEXT'], '.txt')

使用数组来存储所有旧扩展并遍历它们。

【讨论】:

  • 这是一种有趣的方法并且信息量很大。谢谢。
【解决方案3】:

基本思路是先获取文件扩展名部分和真实文件名部分,然后将文件名放入一个新字符串中。

os.path.splitext(p) 方法将有助于获取文件扩展名,例如:os.path.splitext('hello.world.aaa.txt') 将返回 ['hello.world.aaa', '.txt'],它将忽略前导点。

所以在这种情况下,可以这样做:

import os
import sys

path = 'C:/Users/dana/Desktop/text_files_2/'

for filename in os.listdir(path):
    filename_splitext = os.path.splitext(filename)
    if filename_splitext[1] in ['.rtf', '.py', '.TEXT', '.text']:
        os.rename(os.path.join(path, filename), 
                os.path.join(path, 'file_' + filename_splitext[0] +  '.txt'))

【讨论】:

    【解决方案4】:
    import glob, os
    
    path = 'test/'# your path
    extensions = ['.rtf', '.py', '.TEXT', '.text']
    for file in glob.glob(os.path.join(path, '*.*')):
        file_path, extension = os.path.splitext(file)
        if extension in extensions:
            new_file_name = '{0}.txt'.format(
                os.path.basename(file_path)
            )
        if not new_file_name.startswith('file_'): # check if file allready has 'file_' at beginning
            new_file_name = 'file_{0}'.format( # if not add 
                    new_file_name
            )
    
        new_file = os.path.join(
                os.path.dirname(file_path),
                new_file_name
        )
    
        os.rename(file, new_file)
    
    • file_path, extension = os.path.splitext(file) 获取没有扩展名和扩展名的文件路径 f.e ('dir_name/file_name_without_extension','.extension')
    • os.path.dirname(file_path) 获取目录 f.e 如果 file_path 是 dir1/dir2/file.ext 结果将是 'dir1/dir2'
    • os.path.basename(file_path) 获取不带扩展名的文件名

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多