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

2024-04-25 21:15:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我将它绑定到一个批处理文件.cmd(见下文),并将该批处理文件添加到文本文件的上下文菜单中,所以当我右键单击一个文本文件并选择它时,会弹出一个cmd窗口,并键入要比较的文件的地址。在

批处理文件内容:

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

Python代码:

^{pr2}$

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

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

谢谢你的帮助。在


Tags: 文件代码echo路径脚本cmd内容键入
1条回答
网友
1楼 · 发布于 2024-04-25 21:15:44

终于,我自己想出来了! 我发布了最后的代码,也许这对某些人有帮助。在

# 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,会将用双引号括起来的文件路径复制到其中。我在路径之间使用了重复的双引号来创建一个列表,您可以在代码中看到其余部分。 然而,也有一个缺点,就是你不能把多个文件拖到一起,你应该一个一个地做,但总比什么都不做要好。;)

相关问题 更多 >