【问题标题】:Using Pandas to Rename Files - Truth of the Value Error使用 Pandas 重命名文件 - 值错误的真相
【发布时间】:2018-12-13 12:23:49
【问题描述】:

我正在尝试编写一个程序,允许我使用 Excel 电子表格重命名文件,但我不断收到相同的错误消息。我真的很感激任何帮助。错误是:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

这是我当前的代码:

import os
import pandas as pd

os.chdir('C:\\Users\\sferrier\\Desktop\\Test 1')
xl = pd.read_excel('rename_test.xlsx')
df = pd.DataFrame(xl, columns=["Orginal File Name","New File Name"])

for file in os.listdir():
    if file == df["Orginal File Name"]:
        os.rename(file, df["New File Name"])
    else:
        print(file + "was not renamed")

【问题讨论】:

    标签: python-3.x pandas python-os


    【解决方案1】:

    在构造df之后试试这个:

    for x in df.values.tolist():
        os.rename(x[0], x[1])
    

    或者如果你喜欢明确的变量名:

    for index, row in df.iterrows():
        os.rename(row["Orginal File Name"], row["New File Name"])
    

    【讨论】:

      【解决方案2】:

      问题出在这个区块

      for file in os.listdir():
          if file == df["Orginal File Name"]:
              os.rename(file, df["New File Name"])
          else:
              print(file + "was not renamed")
      

      具体来说,在这一行-

      if file == df["Orginal File Name"]:
      

      这一行的问题在于变量file 是一个字符串,而df["Orginal File Name"] 是一整列。因此,本质上,您正在尝试将单个字符串与包含一大堆字符串的数组进行比较。

      要纠正这个问题,您可以像这样遍历行

      for file in os.listdir():
          for index, row in df.iterrows():
              os.rename(row["Orginal File Name"], row["New File Name"])
      

      编辑

      OP 获得的FileNotFoundError 可能是因为您的数据框中有一个文件名实际上并不存在于目录中。您可以运行以下代码块

      for file in os.listdir():
          for index, row in df.iterrows():
              try:
                  os.rename(row["Orginal File Name"], row["New File Name"])
              except:
                  print(row["Orginal File Name"])
      

      即使文件不存在于您的目录中,此块也允许您继续前进,并将打印出不存在的文件的名称。

      【讨论】:

      • 非常感谢。这行得通。它确实以 FileNotFoundError 结尾,只是传递错误是糟糕的编程吗?
      • 再次感谢您,它的工作原理不会以错误结束。下次当我的代码以错误结束时,我将使用 Try 和 except。
      猜你喜欢
      • 1970-01-01
      • 2019-12-01
      • 2014-01-20
      • 2017-12-28
      • 2018-10-30
      • 2020-05-29
      • 2020-09-28
      • 2015-01-14
      • 1970-01-01
      相关资源
      最近更新 更多