简体   繁体   English

将套接字模块的输出写入文件

[英]Write the output of socket module into a file

I'm trying to get the hostname of my computer and then write it to a file. 我正在尝试获取计算机的主机名,然后将其写入文件。 This is what I've got so far, but its not working, where am I going wrong? 到目前为止,这是我所能获得的,但是它不起作用,我在哪里出错?

def testing():
    os.mkdir("zzzdirectory")
    os.chdir("zzzdirectory")
    fo=open("testfolder.txt", "wb")
    fo.write("this is the first line of the file\n")
    s=socket.gethostname()
    fo.write(s)
    fo.close()

testing()

It seems you are not importing the required modules. 似乎您没有导入所需的模块。 Also, you should try & use the with statement for file handling. 另外,您应该尝试使用with语句进行文件处理。 It is more pythonic. 它更pythonic。

import os
import socket

def testing():
    os.mkdir("zzzdirectory")
    os.chdir("zzzdirectory")
    s=socket.gethostname()
    with open("testfolder.txt", "wb") as fo:
        fo.write("this is the first line of the file\n")
        fo.write(s)

testing()

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

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