基于CSV文件值重命名文件-Python

发布于 2025-02-07 17:38:44 字数 532 浏览 1 评论 0原文

我有一个带有名为“ id”的列的CSV文件,并且我有一个带有文件的目录。我想根据“ ID”列下方的单元格中的值重命名这些文件。

我有以下代码:

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id']
    os.rename(file, new_file_name)
   
    i = i + 1

它返回以下错误:

typeError:重命名:DST应该是字符串,字节或OS。类似于Pathike,而不是

我认为这应该非常容易,但是由于我给出了第一步感谢。

谢谢你!

I have a CSV file with a column called "id" and I have a directory with files.I would like to rename those files according to the values that are in the cells below the "id" column.

I have the following code:

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id']
    os.rename(file, new_file_name)
   
    i = i + 1

It returns the following error:

TypeError: rename: dst should be string, bytes or os.PathLike, not Series

I imagine it should be quite easy, but because I am giving the first steps all the help would be appreciated.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似狗非友 2025-02-14 17:38:44

您需要编写DF ['ID']。iLoc [i],而不是DF ['ID'],因为DF ['ID']会给您一系列值,即整列,而不是单个值,为什么您会得到错误

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id'].iloc[i]
    os.rename(path+'/'+file, path+'/'+new_file_name)
   
    i = i + 1

instead of df['id'] you need to write df['id'].iloc[i] because df['id'] will give you series of value i.e whole column instead of single value that why you are getting error

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id'].iloc[i]
    os.rename(path+'/'+file, path+'/'+new_file_name)
   
    i = i + 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文