简体   繁体   English

Python - 将文本添加到具有特定格式的文件中

[英]Python - adding text to a file with a specific format

I guys the textfiles have a certain structure, and I would like to insert my text exactly in this structure.我的文本文件有一定的结构,我想在这个结构中准确地插入我的文本。 For this I have to save a number of character (placeholder) for certain columns and only after this number should I continue writing.为此,我必须为某些列保存一些字符(占位符),只有在这个数字之后我才能继续写作。 Its hard to explain.很难解释。

You can use string formatting for this.您可以为此使用字符串格式。

row = " -  {:<13} {:<10} {:<10} {:-<1} {:-<1} {:-<1}".format(version, date, id_, marker[0], marker[1], marker[2])
file.write(row)

See here for examples on string formatting with padding.有关带填充的字符串格式的示例,请参见此处

What i used here:我在这里使用的:

  • Placeholders are encapsulated with {}占位符用{}封装
  • The colon : separates the paceholder name (not used here) and the formatting冒号:分隔起搏器名称(此处未使用)和格式
  • The < says text should be left-aligned <表示文本应该左对齐
  • The number after the < says how much space should be used at minimum for each word <后面的数字表示每个单词至少应该使用多少空间
  • The - between the colon and the < is the fill character.冒号和<之间的-是填充字符。 Usually, this is a space, but your A, B, C - columns have a - to indicate nothing, so if you were to insert an empty string, it would print a - instead.通常,这是一个空格,但是您的 A、B、C - 列有一个-表示没有任何内容,因此如果您要插入一个空字符串,它将打印一个-代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM