在python3中写入文件

时间:2014-04-08 23:01:02

标签: python-3.x formatting

我是一名蟒蛇初学者。 我正在写一个文件:

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

虽然这是有效的,但它看起来很糟糕(空格和换行是单独的写语句)。

我读了page,但仍然不知道。

如果out.write(datName"\n")无效,有没有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

嗯,你可以做到

out.write(datName + "\n")

但使用print可能更容易:

print(datName, file=out)

print会自动附加换行符。

答案 1 :(得分:0)

如果您希望将许多print语句的输出重定向到文件,可以在Python 3.4+中使用contextlib.redirect_stdout(),对于较旧的Python版本,请参阅this answer

from contextlib import redirect_stdout

with open('init.txt', 'w') as file, redirect_stdout(file):
    print(datName)
    print("T")
    print(datGroup)
    print(datLatx, end="  ")

您还可以组合打印语句:

with open('init.txt', 'w') as file:
    print("\n".join([datName, "T", datGroup, datLatx]),
          end="  ", file=file)
相关问题