在 Python 中写入 txt 文件

Writing to txt file in Python

我在打印到 txt 文件时遇到问题。该文件包含以字节为单位存储的信息。无论我尝试什么,我都只能在 shell 中打印输出。这就是我所拥有的 - 欢迎任何帮助。

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() 内呼叫 print ord(byte)。这会打印到控制台。

您还调用了 f.write(main()),它似乎假设 main() 将要 return 一个值,但它不会.

看起来您打算做的是将 print ord(byte) 替换为将所需输出附加到字符串的语句,然后 return 来自 main() 函数的字符串.

您需要 return 来自函数 main 的字符串。您目前正在打印它,return什么也没有。这将 assemble 字符串和 return 它

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()

这是对各种函数和方法的作用的根本误解。您正在将 main() 的 returned 值写入文件,期望 mainprint() 调用转到该文件。它不是那样工作的。

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() 必须 return 包含您要编写的内容的完整字符串。