Python代码复制DOS Copy命令 – 二进制

huangapple go评论92阅读模式
英文:

Python code to replicate DOS Copy command - Binary

问题

在DOS中有一个简单的命令:copy /b file1 file2 file3 这将执行二进制复制,将file1+file2连接起来输出为file3。

可能看起来有点奇怪,但我需要将一个现有的文件(xml)附加为第一部分,然后将一个pdf文件附加为第二部分。这将在打印文件(pdf)上附加一个“打印”票证。我看到的所有示例都是“合并”文本文件 - 不是我所需要的。我已经可以在DOS中执行此操作,但我不想使用它 - 我需要这个功能在我的Python脚本中,该脚本已经执行了许多其他已经运行良好的操作。

感谢任何提示或想法!

在线上找不到与我的搜索匹配的内容,也找不到类似的描述使用shutil.copy()命令。

英文:

In DOS there is a simple command: copy /b file1 file2 file3 This will do a Binary copy that concatenates file1+file2 outputting file3.

It may seem odd but I need to attach an existing file (xml) as part 1 and then a pdf file as part 2. This attaches a 'print' ticket to a print file(pdf). All the samples I see are 'merging' text files - NOT what I need. I can already do this in DOS but I dont want to use it - I need this functionality inside my Python script that is doing many other things that already work great.

Thanks for any tips or ideas!

Cannot find online any matches to my searches and cannot find similar descriptions using shutil.copy() commands.

答案1

得分: 1

你可以使用简单的文件操作来追加二进制文件

def append_bin_files(file1, file2, output_file):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2, open(output_file, 'wb') as fo:
        fo.write(f1.read())
        fo.write(f2.read())

# 使用这个函数
append_bin_files('message.xml', 'ticket.pdf', 'output.bin')

对于适合内存的较小文件(使用read()函数),这是可以的。

英文:

You can append binary files with simple file operations:

def append_bin_files(file1, file2, output_file):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2, open(output_file, 'wb') as fo:
        fo.write(f1.read())
        fo.write(f2.read())

# use the function
append_bin_files('message.xml', 'ticket.pdf', 'output.bin')

This is fine for smaller files, which fit well into memory (using read() function).

huangapple
  • 本文由 发表于 2023年6月15日 13:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定