python - 如何从文本文件上下文菜单运行 python 脚本并将其与其他文本文件进行比较?
问题描述
我编写了一个 python 脚本,它将两个文件作为输入,然后将它们之间的差异作为输出保存在另一个文件中。
我将它绑定到一个批处理文件.cmd
(见下文)并将批处理文件添加到文本文件的上下文菜单中,所以当我右键单击一个文本文件并选择它时,会cmd
弹出一个窗口并输入文件的地址相比。
批处理文件内容:
@echo off
cls
python "C:\Users\User\Desktop\Difference of Two Files.py" %1
蟒蛇代码:
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
,将用双引号括起来的文件路径复制到其中。我使用路径之间重复的双引号来创建一个列表,您可以在代码中看到其余部分。但是,有一个缺点,就是你不能将多个文件拖到一起,你应该一个一个地做,但总比没有好。;)
推荐阅读
- ruby-on-rails - 有没有办法让 smart_listing 立即跳转到最后一页?
- php - 如何在 php 中将 tinyint 值更新为 1 而不是变为 NULL
- apache-spark - 当数据大小远大于 Cluster 中的可用内存时,Spark 如何进行内存计算
- javascript - 我无法理解特定的“this”绑定
- sparql - 使用命令行在jena tdb中读取多个查询?
- sql-server - 如何使用 T-SQL 中两个不同表中的值调用 Levenshtien 函数
- java - 设置和显示名称和电子邮件 Java 对象类
- zsh - zsh:标准错误没有被重定向
- c - C Shell:程序挂在第一个孩子中
- c - *s++ 中发生了什么?