重命名文件夹中的所有 .csv

Renaming all the .csv in a folder

我想重命名所有 .csv 文件以假设说 mac&cheese_12012010、mac&cheese_13012010、mac&cheese_14012010, mac&cheese_15012010, mac&cheese_16012010....... 只到'_'之后的部分。 我想基本上删除 mac&cheese 并保留 python.

中的日期

你可以运行这个代码在文件所在的目录

import os

# ONELINER
[os.rename(f, f.replace("mac&cheese_", "")) for f in os.listdir() if f.endswith(".csv")]

for file in os.listdir():
    if file.endswith(".csv"):
        os.rename(file, file.replace("mac&cheese_", ""))

import os

# Change the directory
folder = r'E:\demos\files\reports\'
# For Windows folder = r'E:/demos/files/reports/'

for file_name in os.listdir(folder):
    if file_name.endswith(".csv"):
        source = folder + file_name
    
        # We only want the dates
        destination = file_name.split('_')[1] +".csv"

        # Renaming the file
        os.rename(source, destination)

您可以使用 os.rename.

import glob, os

for old in glob.glob('mac&cheese_*.csv'):
    new = old[len('mac&cheese_'):]
    os.rename(old, new)

请注意,在 linux 上,它似乎会覆盖目标文件(如果存在)。在 Windows 上,它似乎不会覆盖文件。无论如何,在处理文件时要谨慎

此外,使用 python 3.9+,您可以替换

new = old[len('mac&cheese_'):]

new = old.removeprefix('mac&cheese_')

这对可读性更好。只是不要使用old.lstrip().

请继续阅读如何提出一个好的问题并提供可重现的数据集。要回答您的问题,有多种方法,包括:

import glob
import os
files = glob.glob('/path/to/files/*.csv')
for file in files:
    new_name = file.replace('mac&cheese_','')
    os.rename(file,new_name)