【问题标题】:Renaming all the .csv in a folder [closed]重命名文件夹中的所有 .csv [关闭]
【发布时间】:2021-11-13 20:15:17
【问题描述】:

我想将所有 .csv 文件重命名为假设 mac&cheese_12012010、mac&cheese_13012010、mac&cheese_14012010、mac&cheese_15012010、mac&cheese_16012010.......仅在“_”之后的部分。 我想基本上删除 mac&cheese 并在 python 中保留日期。

【问题讨论】:

  • 你自己试过什么?你遇到了什么问题?请分享您的代码,人们将能够帮助您解决您可能遇到的问题。

标签: python csv operating-system


【解决方案1】:
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)

【讨论】:

  • 您好,无论是否为 CSV 文件,您的回答都会重命名文件。
  • 谢谢,我已编辑添加对 CSV 文件的验证。
【解决方案2】:

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

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_", ""))

【讨论】:

    【解决方案3】:

    您可以使用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()

    【讨论】:

      【解决方案4】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2013-04-24
        • 2016-07-15
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        • 2016-07-04
        • 2013-06-20
        相关资源
        最近更新 更多