关于批量文件重命名的问题
代码不知道哪里有问题,改完名总是会少一位数
比如应该改成张1233.txt结果实际改成了 张123.txt
import tkinter as tk
from tkinter import filedialog
import os
from tkinter import messagebox
# 创建窗口
window = tk.Tk()
# 设置窗口标题
window.title("My Window")
# 设置窗口大小
window.geometry("520x500")
# 计算居中位置
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = (screen_width - window.winfo_reqwidth()) / 2
y = (screen_height - window.winfo_reqheight()) / 2
# 设置窗口位置
window.geometry("+%d+%d" % (x, y))
# 创建顶部输入框
top_entry = tk.Entry(window)
top_entry.place(x=50, y=10, width=400,height=25)
# 创建顶部按钮
def choose_folder():
default_dir = os.getcwd()
folder_path = filedialog.askdirectory(initialdir=default_dir)
top_entry.delete(0, tk.END)
top_entry.insert(0, folder_path)
top_button = tk.Button(window, text="选择目录", command=choose_folder)
top_button.place(x=430, y=10)
# 创建左侧多行输入框控件和滚动条
left_text = tk.Text(window)
left_text.place(x=10, y=120, anchor="w", width=480,height=150 )
left_scrollbar = tk.Scrollbar(left_text)
left_scrollbar.place(x=460, y=0, height=145)
left_text.config(yscrollcommand=left_scrollbar.set, wrap="char")
# 设置左侧多行输入框控件的大小
left_text.config(width=30, height=10)
left_scrollbar.config(command=left_text.yview)
# 创建右侧多行输入框控件和滚动条
#right_text.place(x=left_text.winfo_x() + left_text.winfo_width(), y=200, anchor="w")
right_text = tk.Text(window)
right_text.place(x=10, y=300, anchor="w", width=480,height=150)
right_scrollbar = tk.Scrollbar(right_text )
right_scrollbar.place(x=460, y=0, height=145)
right_text.config(yscrollcommand=right_scrollbar.set, wrap="word")
# 设置右侧多行输入框控件的大小
right_text.config(width=30, height=10)
right_scrollbar.config(command=right_text.yview)
def rename_txt_files(folder_path, left_text, right_text):
lines = left_text.get("1.0", "end").split("\n")
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt") and any(line in file for line in lines):
old_name = os.path.join(root, file)
line_num = lines.index()
new_name = os.path.join(root, right_text.get(f"{line_num+1}.0", f"{line_num+1}.end-1c").strip() + ".txt")
print(new_name)
if os.path.exists(new_name):
#messagebox.showwarning("警告", f"文件名 {new_name} 已存在!")
print("警告", f"文件名 {new_name} 已存在!")
else:
try:
os.rename(old_name, new_name)
except Exception as e:
print("错误", f"重命名文件 {old_name} 为 {new_name} 时出错:{e}")
#messagebox.showerror("错误", f"重命名文件 {old_name} 为 {new_name} 时出错:{e}")
# 创建输出按钮
def output_lines():
folder_path = top_entry.get()
if not folder_path:
messagebox.showwarning("警告", "您还没有选择目录!")
return
lines = left_text.get("1.0", "end").split("\n")
lines2 = right_text.get("1.0", "end").split("\n")
rename_txt_files(folder_path, left_text, right_text)
print(left_text)
print(right_text)
#遍历文件夹
output_button = tk.Button(window, text="输出每行内容", command=output_lines)
output_button.place(x=210, y=390)
# 运行窗口
window.mainloop()
问题出在这一行代码:
line_num = lines.index()
这里使用了列表推导式,但是如果有多个匹配的行,它只会返回第一个匹配的行,导致重命名时少了一位数。为了解决这个问题,我们可以使用一个循环来查找匹配的行,如下所示:
for line in lines:
if line in file:
line_num = lines.index(line)
break
这样就可以找到所有匹配的行,并返回第一个匹配的行的索引值。完整代码如下: isdkz 发表于 2023-5-14 17:30
问题出在这一行代码:
line_num = lines.index()
完整的代码呢 isdkz 发表于 2023-5-14 17:30
问题出在这一行代码:
line_num = lines.index()
测试了 还是有问题, 重命名会少一位 在 `rename_txt_files` 函数中,文件名的获取可能出现问题导致名称缺失一位数。具体来说,当文件名中包含多个数字时,函数会将最后一个作为后缀名并删除其他数字。这是因为在 `if file.endswith(".txt") and any(line in file for line in lines):` 这一行代码中,对于任意符合条件的文件名,仅取其中第一个匹配到的字符串作为需要替换的内容。
为了解决这一问题,请修改 `rename_txt_files` 函数中的以下代码:
line_num = lines.index()
new_name = os.path.join(root, right_text.get(f"{line_num+1}.0", f"{line_num+1}.end-1c").strip() + ".txt")
将其改为如下代码:
for line in lines:
if line in file:
new_suffix = right_text.get(f"{lines.index(line)+1}.0", f"{lines.index(line)+1}.end-1c").strip()
break
else:
return
name_without_suffix, _ = os.path.splitext(file)
new_name = os.path.join(root, name_without_suffix + new_suffix + ".txt")
这里使用了一个 `for/else` 构造,在 `for` 循环中遍历所有需要替换的内容,找到第一个匹配文件名的字符串,并用它来得到新的后缀名。如果没有找到,则直接结束函数。得到新的后缀名之后,可以使用 `os.path.splitext` 函数来获取文件名和原来的后缀名,并拼接得到新的完整文件名。 koma610630 发表于 2023-5-14 17:34
测试了 还是有问题, 重命名会少一位
对不起,我之前的解释可能有误,你在这里遇到的问题可能与获取新名称中的行号有关。你的代码在使用 "right_text.get(f"{line_num+1}.0", f"{line_num+1}.end-1c")" 时可能在某些情况下没有得到正确的结果,特别是当 right_text 中的行数少于 left_text 中的行数时。这可能导致你从 right_text 中获取的新文件名字符串比预期的短。
我认为可以更改代码以确保每次都能正确地从 right_text 中获取新文件名。以下是我对 rename_txt_files 函数的改动:
def rename_txt_files(folder_path, left_text, right_text):
lines = left_text.get("1.0", "end").split("\n")
lines2 = right_text.get("1.0", "end").split("\n")
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt") and any(line in file for line in lines):
old_name = os.path.join(root, file)
line_num = lines.index()
if line_num < len(lines2):
new_name = os.path.join(root, lines2.strip() + ".txt")
print(new_name)
if os.path.exists(new_name):
print("警告", f"文件名 {new_name} 已存在!")
else:
try:
os.rename(old_name, new_name)
except Exception as e:
print("错误", f"重命名文件 {old_name} 为 {new_name} 时出错:{e}")
else:
print("错误", f"在右侧文本框中找不到对应的新文件名")
在这个改动中,我首先将 right_text 的所有行读入一个名为 lines2 的列表中。然后,每次获取新的文件名时,我会检查 line_num 是否小于 lines2 的长度。如果是,我会使用 lines2 作为新的文件名。如果不是,我会打印一个错误消息。这样可以确保我们不会试图从 right_text 中获取一个不存在的行。
希望这个改动能帮助你解决问题。如果仍然存在问题,请告诉我,我会尽力帮助你解决。 sfqxx 发表于 2023-5-14 17:44
在 `rename_txt_files` 函数中,文件名的获取可能出现问题导致名称缺失一位数。具体来说,当文件名中包含多 ...
还是不行, 重命名还是会少一位。
页:
[1]