python改文件名_如何使用Python更改目录中的多个文件名

1586010002-jmsa.png

I am learning Python and I have been tasked with:

adding "file_" to the beginning of each name in a directory

changing the extension (directory contains 4 different types currently: .py, .TEXT, .rtf, .text)

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)

I do still have a bit of a problem:

the script currently must be inside my directory for it to run.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值