Skip to main content
 首页 » 编程设计

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

2025年05月04日14开发

我正在尝试获取计算机的主机名,然后将其写入文件。这是我到目前为止所得到的,但它不起作用,我哪里出错了?

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

请您参考如下方法:

看来您没有导入所需的模块。此外,您应该尝试使用 with 语句来处理文件。它更像 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()