Python 基于.csv文件重新命名文件。在字典中循环作为向导

Python 基于.csv文件重新命名文件。在字典中循环作为向导,python,loops,csv,dictionary,Python,Loops,Csv,Dictionary,我编写了一个脚本,读取一个两列的.csv文件,将其转换为一个字典,然后将其用作重命名目录中文件的指南。如果文件与指南词典中的键匹配,则将其重命名为值。问题是它只重命名一个文件,然后停止;它不会在我的导游词典中循环出现。它重命名一个文件,然后停止。Python和stackoverflow是新手,因此欢迎您提供任何反馈 目录只是一个文件列表 Barcode85.fq Barcode73.fq Barcode61.fq Barcode86.fq .csv文件的结构如下所示,其中第一列是我想要的新文件

我编写了一个脚本,读取一个两列的.csv文件,将其转换为一个字典,然后将其用作重命名目录中文件的指南。如果文件与指南词典中的键匹配,则将其重命名为值。问题是它只重命名一个文件,然后停止;它不会在我的导游词典中循环出现。它重命名一个文件,然后停止。Python和stackoverflow是新手,因此欢迎您提供任何反馈

目录只是一个文件列表

Barcode85.fq
Barcode73.fq
Barcode61.fq
Barcode86.fq
.csv文件的结构如下所示,其中第一列是我想要的新文件名,secodn条形码是现在的文件名:

wtcother1.3.4.fq, Barcode85.fq
wtcother2.fq, Barcode73.fq
wtcother6.fq, Barcode61.fq
wtcother6.fq, Barcode86.fq
ect.
创建的字典如下所示:

['wtcother1.3.4.fq', 'Barcode85.fq']
['wtcother2.fq', 'Barcode73.fq']
['wtcother6.fq', 'Barcode61.fq']
['wtcmbr1.4.6.fq', 'Barcode86.fq']
ect.
脚本如下:

import os
import csv

# make an empty dictionary which will hold the keys
keys = {}

#open file
with open('lane1Key.csv','rU') as csvfile:
        reader = csv.reader(csvfile, delimiter = ',', quotechar='"')
# build a dictionary with the associated ids
        for rowDict in reader:
              keys[ rowDict[0] ] = rowDict[1]
              print rowDict
# renaming
for fileName in os.listdir('.'):
    if fileName in rowDict:
        os.rename(fileName, rowDict[0])

提前感谢您的时间。

您不需要浏览所有文件,只需浏览字典中的文件即可:

for k in keys:
    os.rename(k, keys[k])
请注意,您可能混淆了第一列和第二列

# renaming
for fileName in ( os.listdir('.') & keys.keys() ):
    os.rename(fileName, keys[fileName])
这将在找到的文件和csv中定义的文件的交集上迭代

如果无法更改csv文件中列的顺序,则需要调整:

# build a dictionary with the associated ids
        for rowDict in reader:
              keys[ rowDict[1] ] = rowDict[0]