Python中文件输出的空格

时间:2017-08-18 11:45:19

标签: python python-2.7

我正在用C语言进行Python编程:

开发脚本以执行一些自动化作业。 我正在将数据写入一个文件,如下所示,

f.write("    hallo")
f.write(""+""+""+""+"hallo")

我想在写作之前给出4个空格。

我尝试过这些选项:

<?php

但我无法实现我想要的目标。

3 个答案:

答案 0 :(得分:1)

with open("demo.txt", "w") as f: # open file demo.txt in write mode
    f.write("    hallo")

不知道你遇到了什么麻烦但是通过这种方式你可以得到用四个空格写成的文本文件demo.txt和你好

demo.txt

    hallo

有很多方法可以实现这一点,即假设你要打印Hello前面有n个空格:

v = " "*n + "Hello" #  '    Hello' (i have used n=4)

另一个例子:

spaces = " "*10  # 10 spaces
new_line = "\n"*2 # two new lines
string = "Hello"
final = spaces + new_line + string
with open("demo.txt", "w") as f:
    f.write(final)

注意:如果您在写入模式下重新打开现有文件,它将清除文件的所有内容,然后开始编写内容

答案 1 :(得分:0)

f.write("    hallo") # give manu

f.write(" " + " " + " " + " " + "hallo")

答案 2 :(得分:0)

如评论中所述:

f.write((" " * 4) + "hallo")

这将是完美的。