簡體   English   中英

如何用python重命名文件?

[英]How to rename files with python?

我需要幫助更正此錯誤

import os

def rename_file () :
    # 1. get file names from a folder
    file_list = os.listdir(r"E:\Downloads\prank\prank")
    #print (file_list)
    saved_path = os.getcwd()
    print ("current working directory is "+saved_path)
    os.chdir (r"E:\Downloads\prank\prank")

    # 2. for each file, rename filename
    for file_name in file_list:
    os.rename(file_name, file_name.translate(None,"0123456789"))
    os.chdir(saved_path)     
rename_file()    

在此先感謝您的幫助。

您沒有發布錯誤,並且不清楚要將文件重命名為什么。 也許您想將 '0123456789' 連接到文件名? 我會做一個約會,因為它更有意義。 因此,這與您提供的內容一樣好。 在這種情況下,有一個包含 5 個文件的目錄,我們將為每個文件添加日期。 文件所在的目錄稱為“源文件”。 腳本的源代碼與“source_files”位於同一父目錄中。 此腳本更改它們所在目錄中的文件名。當然,如果您願意,您可以將它們保存在不同的目錄中。 文件名是:file001.txt、file002.txt、file003.txt、file004.txt 和 file005.txt。 目錄路徑適用於我的計算機,因此您必須對其進行必要的更改才能在您的計算機上運行。

#!python2

import os.path

# directory path to files for name change
source = r'P:\python\stackoverflow\source_files'

# string that will be concatenated to file name
add_date = '20180406'

# make a list of the files and print them
get_files = os.listdir(source)
print get_files, '\n\n'

# change the file names
for item in get_files:
    os.rename(source + '\\' + item, source + '\\' + '20180406_' + item)

# get the files and print their new names
get_files = os.listdir(source)
print get_files
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

作為獎勵,這里介紹了如何更改文件擴展名。

# directory path to files for name change
source = r'P:\python\stackoverflow\source_files'

# make a list of the files and print them
get_files = os.listdir(source)
print get_files, '\n\n'

# change the file name extensions from .txt to .dat
for item in get_files:
    os.rename(source + '\\' + item, source + '\\' + item[0: -3] + 'dat')

# get the files and print their new names
get_files = os.listdir(source)
print get_files

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM