python查找文件并重命名_Python,如何根据列表重命名几个文件?

1586010002-jmsa.png

Using python with Windows Im trying to rename several files at once that are in the same folder but I cant use a list to do a rename that is why I get this error when I try my code:

os.rename(dirlist[1], words[1]) WindowsError: [Error 2] The system

cannot find the file specified

Here is the sample code:

import os

import sys

words = os.listdir('C:/Users/Any/Desktop/test')

dirlist = os.listdir('C:/Users/Any/Desktop/test')

words = [w.replace('E', 'e') for w in words]

print words

os.rename(dirlist[1], words[1])

What I am trying to achieve is have my python script ran on a folder of choice and the script will take all the files in there and will rename all of them. But the tricky part comes when I cant single out the folder names and have them renamed because they are attached to the list.

解决方案

os.listdir is only giving you back the basename results. Not full path. They don't exist in your current working directory. You would need to join them back with the root:

root = 'C:/Users/Any/Desktop/test'

for item in os.listdir(root):

fullpath = os.path.join(root, item)

os.rename(fullpath, fullpath.replace('E', 'e'))

Update

In response to your comment about how to perform larger number of replacements, I had suggested you could use translate and maketrans.

Let's start with our dict and a source string:

d = {'E': 'e', 'a': 'B', 'v': 'C'}

s = 'aAaAvVvVeEeE'

First, let me show you an example of a very primitive and entry level approach:

for old, new in d.iteritems():

s = s.replace(old, new)

print s

# BABACVCVeeee

That example loops over your dictionary, calling the replacement multiple times. It works, and it makes perfect sense, using simple syntax. But it kind of sucks having to loop over the dictionary for every string and call replace multiple times.

There are many other ways to do this I am sure, but another approach is to create a translation table once, and then reuse it for every string:

import string

old, new = zip(*d.items())

print old, new

# ('a', 'E', 'v') ('B', 'e', 'C')

old_str, new_str = ''.join(old), ''.join(new)

print old_str, new_str

# aEv BeC

table = string.maketrans(old_str, new_str)

print s.translate(table)

# BABACVCVeeee

That will split the dictionary out to key and value tuples. Then we join then intro strings and pass them to maketrans, which will give us back a table. We only have to do that once. Now we have a table and can use it to translate any string.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值