我编写了一个python脚本,通过删除文件名中的所有数字来重命名文件夹中存在的所有文件,但这不起作用。 注意:相同的代码适用于python2.7
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
#(2) for each file ,rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
任何人都可以告诉我如何使它工作。是翻译功能无法正常工作
答案 0 :(得分:1)
问题在于代码的os.rename()部分。
os.rename()要求您为要更改它的文件/文件夹提供完整路径,而您只给它file_name而不是完整路径。
您必须添加文件夹/文件目录的完整路径。 所以看起来应该是这样的:
def rename_files():
# add the folder path
folder_path = "D:\prank\\"
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
# Concat the folder_path with file_name to create the full path.
for file_name in file_list:
full_path = folder_path + file_name
print (full_path) # See the full path here.
os.rename(full_path, full_path.translate(None, "0123456789"))
答案 1 :(得分:0)
查看os的文档,以及我在重命名时发现的内容:
os.rename(src,dst,*,src_dir_fd = None,dst_dir_fd = None)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use replace().
New in version 3.3: The src_dir_fd and dst_dir_fd arguments.
下载文档的链接,希望这有帮助,谢谢
答案 2 :(得分:0)
其他人已经指出了你的代码的其他问题,但是对于你使用translate,在Python 3.x中,你需要传递一个字典映射序数到新值(或None
)。这段代码可行:
import string
...
file_name.translate(dict(ord(c), None for c in string.digits))
但这似乎更容易理解:
import re
...
re.sub(r'\d', '', file_name)