简体   繁体   English

用Python写入txt文件

[英]Writing to txt file in Python

I'm having issues printing to a txt file. 我在打印到txt文件时遇到问题。 The file contains information stored in bytes. 该文件包含以字节为单位存储的信息。 No matter what I try, I can only get the output to print in the shell. 无论我尝试什么,我都只能在外壳程序中打印输出。 Here's what I have - any help is welcome. 这就是我所拥有的-欢迎任何帮助。

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

This is a fundamental misunderstanding of what various functions and methods do. 这是对各种功能和方法的基本误解。 You are writing the returned value of main() to the file, expecting main 's print() calls to go to the file. 您正在将main()的返回值写入文件,期望mainprint()调用转到该文件。 It does not work like that. 它不是那样工作的。

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

Use file.write() to write strings (or bytes, if you're using that kind of output, which you currently aren't) to a file. 使用file.write()将字符串(或字节,如果您使用的是当前不是当前输出)写入文件。 For your code to work, main() would have to return a complete string with the content you wanted to write. 为了使代码正常工作, main()必须返回包含您要编写的内容的完整字符串。

You are calling print ord(byte) from within main() . 您正在从main()内调用print ord(byte) main() This prints to the console. 这将打印到控制台。

You are also calling f.write(main()) which appears to assume that main() is going to return a value, but it doesn't. 您还调用了f.write(main()) ,它似乎假设main()返回一个值,但事实并非如此。

It looks like what you intend to do is replace the print ord(byte) with a statement that appends your desired output to a string, and then return that string from your main() function. 看起来您打算执行的操作是用一条语句替换print ord(byte) ,该语句将所需的输出附加到字符串,然后从main()函数return该字符串。

You need to return the string from the function main . 您需要从函数main返回字符串。 You are currently printing it and returning nothing. 您当前正在打印它,什么也不返回。 This will assemble the string and return it 这将组装字符串并返回它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM