如何使用变量.format写入文件?

问题描述 投票:0回答:5

我想将两个字符串写入一个文件,并且文件之间要有可变的空格。这是我写的代码:

width = 6
with open(out_file, 'a') as file:
    file.write("{:width}{:width}\n".format('a', 'b'))

但是我从中得到ValueError: Invalid conversion specification。我希望它可以将字符ab在一行中的6个空格之间写入字符。

我正在使用python 2。

python file python-2.x
5个回答
0
投票

这有点难看,但是你可以做到这一点。使用{{}}可以键入文字大括号,然后,可以使用可变宽度设置格式字符串的格式。

width = 6

format_str = "{{:{}}}{{:{}}}\n".format(width, width) #This makes the string "{:width}{:width}" with a variable width.


with open(out_file, a) as file:
    file.write(format_str.format('a','b'))

0
投票

我在Google上搜索了一下,找到了this。经过一些更改,我编写了这段代码,尝试并获得了所需的输出:

width = 6
with open(out_file, 'a') as file:
    f.write("{1:<{0}}{2}\n".format(width, 'a', 'b'))

0
投票

一个简单的乘法将在这里工作(乘法运算符在这里超载)

width = 6
charector = ' '
with open(out_file, 'a') as file:
    file.write('a' + charector * width + 'b')

0
投票

您需要稍微更改格式字符串,并将width作为关键字参数传递给format()方法:

width = 6
with open(out_file, 'a') as file:
    file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))

之后的文件内容:

a     b     

-2
投票

如果要使用这种格式,可以使用file()参数使用print()写入文件,例如:

width = 6
with open(out_file, 'a') as f:
    print("{:width}{:width}\n".format('a','b'), file=f)
© www.soinside.com 2019 - 2024. All rights reserved.