Python 在文件中写入变量
我正在创建这个“hextump”程序,我遇到的问题是写入文件,因为我需要它将数据转储到一个文件中,而不是保存在终端中 附言:我对Python有点陌生,所以我的朋友帮我编写了这个 代码如下:Python 在文件中写入变量,python,printing,hex,dump,Python,Printing,Hex,Dump,我正在创建这个“hextump”程序,我遇到的问题是写入文件,因为我需要它将数据转储到一个文件中,而不是保存在终端中 附言:我对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" %
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)
我知道它非常混乱,但我需要在文件中打印数据。要附加到文件,需要使用“a”模式而不是“w”(覆盖),如下所示:
f = open('dump.txt', 'a')
但是,在酸洗(将对象保存到文件中)的情况下,您可能希望根据以下答案修改代码:
要附加到文件,需要使用“a”模式而不是“w”(覆盖),如下所示:
f = open('dump.txt', 'a')
但是,在酸洗(将对象保存到文件中)的情况下,您可能希望根据以下答案修改代码:
使用此代码,它可以完美地工作:
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”?使用此代码,它可以完美地工作:
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”?p.S:它只写最后一行:/fix
中的缩进,但它仍然在我的文件中打印一行:(不,您正在覆盖以前的内容。我认为您是对的,因为它只打印最后一行,所以有没有建议让它打印所有内容??p.s:它只写最后一行:/Fixed在for
loopfixed中的缩进,但它仍然在我的文件中打印一行:(没有。您正在覆盖以前的内容。我认为您是对的,因为它只打印最后一行,所以有没有建议让它打印所有内容??谢谢它工作了,但我希望输出格式如下:69 6d 70 6f 72 20 73 73 0d 0a 69 6d 70 6f(这里是Ascii)它工作得很好,谢谢,但在每一行的每一端它都写“p0”,每一行都以“.S”开头。有什么想法吗?谢谢,它工作得很好,但我希望输出格式如下:69 6d 70 6f 72 74 20 73 79 73 0d 0a 69 6d 70 6f(这里是Ascii)它工作得很好,谢谢,但在每一行的每一端它都写“p0”每行都以“.S”开头有什么想法吗?