2

I wrote a function in Python to sort my data into a dictionary syntax, but because I'm using while, there is a comma that I would like to remove to avoid having an invalid syntax.

For example with the following code:

file = open("test.txt","w", encoding="utf-8")
number = 0
while number < 5:
    file.write("some text" + ", ")
    number += 1

This will create test.txt with the following text inside:

some text, some text, some text, some text, some text,

I would like to remove the last ", " added by at the end to look like:

some text, some text, some text, some text, some text

Any idea?

2
  • 1
    One suggestion: construct the entire sentence first (using .join methods if it is a list or something) and write one sentence at a time. essentially, dont use the inner while loop, but instead construct and write a sentence at a time. Commented Feb 20, 2019 at 14:22
  • Remark: The script I actually is longer than the example I wrote above and includes several "if, elif, ...". This is way I'm looking for a simple way to just delete the very last chars of the file. One solution I have is to close() the file, re-open it and using x = x[:-1] to delete the last chars, but I'm sure there is a better way to achieve it. Commented Feb 20, 2019 at 14:32

4 Answers 4

3

I would use join

text_to_write = 5 * ['the text']
file.write(', '.join(text_to_write))
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

file = open("test.txt","w", encoding="utf-8")
number = 0
list_to_add = []
while number < 5:
    list_to_add.append("some text") # you can append anything based_on iteration
    number += 1
file.write(','.join(list_to_add))

Comments

1

It is possible to do the same thing without while loop:

file = open("test.txt","w", encoding="utf-8")
file.write(", ".join(["some text"] * 5))

", ".join([ ... ]) function joins multiple strings of text in a list using a seperator ,, in your case that equals to:

In [1]: ", ".join(["some text"] * 5)
Out[1]: 'some text, some text, some text, some text, some text'

Comments

1

simply use a different command for the last element.

file = open("test.txt","w", encoding="utf-8")
number = 0
while number < 5:
    file.write("some text" + ", ")
    if(number == 4):
           file.write("some text") 
    number += 1

2 Comments

This would work without problem but as my actual "while" loop is much longer than the one above I would have to repeat twice the code.
well, you could use an if condition that is active in the last iteration of your algorithm. Below that condition you modify the write command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.