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