Python 3.x 在python3中写入文件
我是python初学者。 我正在以以下身份写入文件:Python 3.x 在python3中写入文件,python-3.x,formatting,Python 3.x,Formatting,我是python初学者。 我正在以以下身份写入文件: with open("Init", mode='w') as out: out.write(datName) out.write("\n") out.write("T\n") out.write(datGroup) out.write("\n") out.write(datLatx) out.write(" ") 虽然这是工作,但它看起来很糟糕(空格和换行符是单
with open("Init", mode='w') as out:
out.write(datName)
out.write("\n")
out.write("T\n")
out.write(datGroup)
out.write("\n")
out.write(datLatx)
out.write(" ")
虽然这是工作,但它看起来很糟糕(空格和换行符是单独的写语句)
我读了这篇文章,但还是不知道
如果输出,是否有更好的方法执行此操作。write(datName“\n”)
无效?好的,您可以这样做
out.write(datName + "\n")
但是使用打印可能更容易:
print(datName, file=out)
由于print
会自动添加换行符。如果希望将许多print语句的输出重定向到文件,可以在Python 3.4+中使用,对于较旧的Python版本,请参阅:
您还可以组合打印语句:
with open('init.txt', 'w') as file:
print("\n".join([datName, "T", datGroup, datLatx]),
end=" ", file=file)
with open('init.txt', 'w') as file:
print("\n".join([datName, "T", datGroup, datLatx]),
end=" ", file=file)