gpt4 book ai didi

python - 如何从文本文件上下文菜单运行 python 脚本并将其与其他文本文件进行比较?

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:33 24 4
gpt4 key购买 nike

我编写了一个 python 脚本,它将两个文件作为输入,然后将它们之间的差异保存为另一个文件中的输出。

我将其绑定(bind)到批处理文件.cmd(见下文)并将批处理文件添加到文本文件的上下文菜单中,因此当我右键单击文本文件并选择它时,弹出 cmd 窗口,我输入要比较的文件的地址。

批处理文件内容:

@echo off
cls
python "C:\Users\User\Desktop\Difference of Two Files.py" %1

Python 代码:

import sys
import os

f1 = open(sys.argv[1], 'r')
f1_name = str(os.path.basename(f1.name)).rsplit('.')[0]

f2_path = input('Enter the path of file to compare: ')
f2 = open(f2_path, 'r')
f2_name = str(os.path.basename(f2.name)).rsplit('.')[0]

f3 = open(f'{f1_name} - {f2_name} diff.txt', 'w')
file1 = set(f1.read().splitlines())
file2 = set(f2.read().splitlines())

difference = file1.difference(file2)

for i in difference:
f3.write(i + '\n')

f1.close()
f2.close()
f3.close()

现在,我的问题是如何使用接受多个文件的拖放解决方案来替换第二个文件路径的输入。

我对 python 代码没有任何问题,并且可以自己扩展它以包含更多文件。我只是不知道如何编辑批处理文件,因此不是通过键入路径仅获取一个文件,而是通过拖放来获取多个文件。

非常感谢您的帮助。

最佳答案

我终于自己弄清楚了!我发布了最终的代码,也许对某人有帮助。

# This script prints those lines in the 1st file that are not in the other added files
# and saves the results into a 3rd file on Desktop.

import sys
import os


f1 = open(sys.argv[1], 'r')
f1_name = str(os.path.basename(f1.name)).rsplit('.')[0]
reference_set = set(f1.read().splitlines())

compare_files = input('Drag and drop files into this window to compare: ')
compare_files = compare_files.strip('"').rstrip('"')
compare_files_list = compare_files.split('\"\"')
compare_set = set()

for file in compare_files_list:
with open(os.path.abspath(file), 'r') as f2:
file_content = set(f2.read().splitlines())
compare_set.update(file_content)


f3 = open(f'C:\\Users\\User\\Desktop\\{f1_name} diff.txt', 'w')

difference = reference_set.difference(compare_set)

for i in difference:
f3.write(i + '\n')

f1.close()
f3.close()

这个想法来自于拖放到 cmd 中,将用双引号括起来的文件路径复制到其中。我在路径之间使用重复的双引号来创建一个列表,您可以在代码中看到其余部分。然而,它有一个缺点,那就是你不能将多个文件拖到一起,你应该一个一个地这样做,但这总比没有好。 ;)

关于python - 如何从文本文件上下文菜单运行 python 脚本并将其与其他文本文件进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54195311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com