joe joe - 2 months ago 53
Python Question

what does with open do in this situation

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
s=sentence.split()
positions = [s.index(x)+1 for x in s]
print(sentence)
print(positions)
with open('task_2.json', 'w') as f:
f.write(str(positions))
f.write(str(sentence))
f.close()


In this task I must develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of the word in the list. It must then compress the positions and send it to a file. I have managed to complete all of the above but im struggling to understand the "with open" part. I have tried just using "open" and the code comes up with a syntax error. So if anyone could explain to me what the keyword "with" does in this situation it would be much appreciated.

Answer

The with open('task_2.json', 'w') as f: closes the file after the indented code runs. This means that you don't need the f.close() line. Using a with statement in python is just a safer way to work with files.

Comments