Writing Text Files

Writing a text file means opening a file in a mode that allows output and then writing strings to it.

The "w" means write mode.

Write mode replaces the file

If the file already exists, "w" starts a new file at that path:

Write mode replaces old contents

Runs locally with Python in your browser.

Ready to run.

The output is only second, because the second write opened the file in write mode again.

Append mode adds to the end

Use "a" when you want to append:

Append mode is useful for logs. For most learning scripts in this subject, write mode is clearer because each run creates a fresh result.

Write strings

file.write expects a string:

The str(count) conversion is explicit. It prevents a type error and makes it clear where numbers become report text.

Newlines are your responsibility

write does not add a newline automatically:

That produces:

line oneline two

Add \n when you want a line break.

Exercise: Write a summary

Edit the code so the final output contains items: 3.

Write then read a file

Runs locally with Python in your browser.

Ready to run.

HintWrite the computed count

Convert len(items) to text with str(...) and include it in the string passed to file.write().

SolutionWrite items and the count

Use file.write("items: " + str(len(items))). The list contains three items, so reading the file back prints items: 3.