我正在制作这个" hexdump"程序,我遇到的问题是写入文件,因为我需要它将数据转储到文件中,而不是将其保存在终端中。
P.S:我对Python有点新意,所以我的朋友帮我编码了。
以下是代码:
import sys
import pickle
def hexdump(fname, start, end, width):
for line in get_lines(fname, int(start), int(end), int(width)):
nums = ["%02x" % ord(c) for c in line]
txt = [fixchar(c) for c in line]
x = " ".join(nums), "".join(txt)
y = ' '.join(x)
print (y)
f = open('dump.txt', 'w')
pickle.dump(y, f)
f.close()
def fixchar(char):
from string import printable
if char not in printable[:-5]:
return "."
return char
def get_lines(fname, start, end, width):
f = open(fname, "rb")
f.seek(start)
chunk = f.read(end-start)
gap = width - (len(chunk) % width)
chunk += gap * '\000'
while chunk:
yield chunk[:width]
chunk = chunk[width:]
if __name__ == '__main__':
try:
hexdump(*sys.argv[1:5])
except TypeError:
hexdump("hexdump.py", 0, 100, 16)
我知道这很乱,但我需要在一个文件中打印数据。
答案 0 :(得分:2)
要附加到文件,您需要使用'a'模式而不是'w'(覆盖),如下所示:
f = open('dump.txt', 'a')
但是,如果是酸洗(将对象保存到文件中),您可能希望根据以下答案修改代码:https://stackoverflow.com/a/12762056/1256112
def hexdump(fname, start, end, width):
with open('dump.txt', 'ab') as writeable:
for line in get_lines(fname, int(start), int(end), int(width)):
nums = ["%02x" % ord(c) for c in line]
txt = [fixchar(c) for c in line]
x = " ".join(nums), "".join(txt)
y = ' '.join(x)
print(y)
pickle.dump(y, writeable)
答案 1 :(得分:1)
使用此代码完美地运作:
def hexdump(fname, start, end, width):
with open('dump.txt', 'ab') as writeable:
for line in get_lines(fname, int(start), int(end), int(width)):
nums = ["%02x" % ord(c) for c in line]
txt = [fixchar(c) for c in line]
x = " ".join(nums), "".join(txt)
y = ' '.join(x)
print(y)
pickle.dump(y, writeable)
现在的问题是,当我打开dump.txt
时,我发现了这个:
S'69 6d 70 6f 72 74 20 73 79 73 0d 0a 69 6d 70 6f import sys..impo'
p0
.S'72 74 20 70 69 63 6b 6c 65 0d 0a 0d 0a 0d 0a 64 rt pickle......d'
p0
那么如何摆脱“S”和“p0”?