繁体   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