用Python写入txt文件
我遇到打印到txt文件的问题。该文件包含以字节存储的信息。无论我尝试什么,我只能得到要在shell中打印的输出。这就是我所拥有的 - 任何帮助都是值得欢迎的。用Python写入txt文件
def main():
with open("in.txt", "rb") as f:
byte = f.read(1)
while byte != "":
print ord(byte),
byte = f.read(1)
with open('out.txt','w') as f:
if __name__ == '__main__':
f.write(main())
close.f()
这是对各种功能和方法的根本误解。您正在将文件main()
的返回值写入文件,期望main
的print()
调用转到该文件。它不这样工作。
def main():
with open("in.txt", "rb") as f, open('out.txt','w') as output:
byte = f.read(1)
while byte != "":
output.write(str(ord(byte)))
byte = f.read(1)
if __name__ == '__main__':
main()
使用file.write()
写入字符串(或字节,如果您使用的输出类型,你目前都没有)到一个文件中。为了让您的代码正常工作,main()
将不得不返回一个完整的字符串和您想要写入的内容。
非常感谢 - 显然我还在学习。我非常感谢你的解释。这似乎解决了这个问题。 – Maggie
您从main()
中调用print ord(byte)
。这会打印到控制台。
您还打电话给f.write(main())
,它似乎假设main()
要去返回一个值,但它不是。
它看起来像你打算做的是用一个语句替换print ord(byte)
,该语句将你想要的输出附加到一个字符串,然后return
这个字符串来自你的main()
函数。
非常感谢! – Maggie
您需要从函数main
返回字符串。您目前正在打印它并不返回任何内容。这将组装字符串并将其返回
def main():
with open("in.txt", "rb") as f:
ret = ""
byte = f.read(1)
while byte != "":
ret = ret + byte
byte = f.read(1)
return ret
with open('out.txt','w') as f:
if __name__ == '__main__':
f.write(main())
close.f()
感谢您的反馈,我可以使用所有的帮助,我可以得到:) – Maggie
你的'main'函数没有返回值 –