如何使用Python更改目录中的多个文件名 [英] How to change multiple filenames in a directory using Python

查看:90
本文介绍了如何使用Python更改目录中的多个文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python,并且承担了以下任务:

I am learning Python and I have been tasked with:

  • 在目录中每个名称的开头添加"file _"
  • 更改扩展名(目录目前包含4种不同的类型:.py,.TEXT,.rtf,.text)

我有很多文件,每个文件都有不同的名称,每个文件长7个字符.我可以更改扩展名,但是感觉很笨拙.我很肯定有一种更干净的方法来编写以下内容(但它可以正常运行,因此在该注释上不会有任何抱怨):

I have many files, all with different names, each 7 characters long. I was able to change the extensions but it feels very clunky. I am positive there is a cleaner way to write the following (but its functioning, so no complaints on that note):

    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 _" [您会以为这很简单].我尝试将新名称声明为

  1. the script currently must be inside my directory for it to run.
  2. I can not figure out how to add "file_" to the start of each of the filenames [you would think that would be the easy part]. I have tried declaring newname as

newname = 'file_' + str(filename)

然后指出文件名未定义.

it then states filename is undefined.

在我现有的两个问题上的任何帮助,将不胜感激.

Any assistance on my two existing issues would be greatly appreciated.

推荐答案

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

The basic idea would be first get the file extension part and the real file name part, then put the filename into a new string.

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

os.path.splitext(p) method will help to get the file extensions, for example: os.path.splitext('hello.world.aaa.txt') will return ['hello.world.aaa', '.txt'], it will ignore the leading dots.

因此,在这种情况下,可以这样完成:

So in this case, it can be done like this:

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'))

这篇关于如何使用Python更改目录中的多个文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆