简体   繁体   中英

Python - remove last character when writing to a file

I'm writing a dict variable into a text file

for key, value in dict.items():
   input_file.write("%s:%s\n" % (key, value))

How can I delete the last \n from the file that is generated?

str.join would take care,

input_file.write(
    "\n".join("%s:%s" % (key, value) for key, value in dict.items())
)

I suggest inserting the \n before the new line, except the first one:

prefix = ''
for key, value in dict.items():
    input_file.write(f'{prefix}{key}:{value}')  # also: modern formatting
    prefix = '\n'

see below

data = {'A':12,'B':34}
for idx,key in enumerate(data.keys()):
   new_line = '' if idx == len(data) -1 else '\n'
   input_file.write("{}:{}{}".format(key, data[key],new_line))

One can print to file. So one can separate k, v pairs with newline and set end to empty string:

print(*(f'{k}: {v}' for k, v in d.items()), sep='\n', end='', file=input_file)

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