重命名多个 csv 文件 [英] Renaming multiple csv files

查看:73
本文介绍了重命名多个 csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:在我的目录中,我有许多文件夹,这些文件夹都包含名称格式如下的 csv 文件:

I have the following problem: in my directories I have numerous folders which all contain csv files with names in the following format:

00000562834-2018-07-27-file-8.csv

为了在 python 中大规模使用这些文件,我必须以公式的形式插入名称(xxxxxxxxxxxx-year-month-day-file-hour").但是,第一个数字(在本例中为 00000562834)是随机的,因此我无法创建自动使用所有文件的代码.

In order to make these files available on scale in python, I have to insert the name in the form of a formula ("xxxxxxxxxxxx-year-month-day-file-hour"). However, the first digits (in this case 00000562834) are random, so I cannot create a code that uses all files automatically.

因此我的问题是:有人知道如何删除所有 csv.files 中的前 12 位数字吗?不幸的是,手动更改所有内容无法扩展.

Hence my question: Does anybody know how I can remove these first 12 digits in all my csv.files? Changing all manually would not scale, unfortunately.

推荐答案

这是使用 pathlib 和 rglob 方法.

Here's a solution using pathlib and the rglob method.

from pathlib import Path
rootfolder = '/home/nicolaso/foo/bar/'  # example

for f in Path(rootfolder).rglob('*-file-*.csv'):
  new_name = f.name.split('-', 1)[1]
  f.rename(f.with_name(new_name))

如果您实际上不想重命名文件,则无论如何都可以在 for 循环中处理它们.

If you don't actually want to rename the files, you can just process them in the for loop anyway.

这篇关于重命名多个 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆