python重命名csv文件_Python重命名文件从csv文件读取名称

Hi there i've been trying to adapt this to my needs but I'm just a newbe in python, I have a csv file with multiple columns and rows, important columns are 1 = old name of file, and 2 = new name of file, so I need to go the directory where the files listed in csv file are and rename them to the new name of column 2, as I say I've tried many things without success, I paste the last code I've made so you have an idea:

import os, unicodecsv as csv, sys

IDs = {}

#open and store the csv file

with open('documentos_corpus_ladino.csv','rb') as csvfile:

timeReader = csv.reader(csvfile, delimiter = ',')

# build a dictionary with the associated IDs

for row in timeReader:

IDs[ row[0] ] = row[1]

# #get the list of files

path = 'txt_orig/'

tmpPath = 'txt_tmp/'

for filename in os.listdir('txt_orig/'):

oldname = filename

newname = filename.replace(oldname, csvfile.next().rstrip().split(",")[1])

os.rename(path + filename, tmpPath + newname)

Thanks a lot.

解决方案

This will rename each matching file, and report any errors trying to rename. It will not attempt to move non-existent files.

import os, unicodecsv as csv

# open and store the csv file

IDs = {}

with open('documentos_corpus_ladino.csv','rb') as csvfile:

timeReader = csv.reader(csvfile, delimiter = ',')

# build dictionary with associated IDs

for row in timeReader:

IDs[row[0]] = row[1]

# move files

path = 'txt_orig/'

tmpPath = 'txt_tmp/'

for oldname in os.listdir(path):

# ignore files in path which aren't in the csv file

if oldname in IDs:

try:

os.rename(os.path.join(path, oldname), os.path.join(tmpPath, IDs[oldname]))

except:

print 'File ' + oldname + ' could not be renamed to ' + IDs[oldname] + '!'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值