简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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