+91 81900 98289

Python Write/Create Files

This Python Write/Create Files lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Mode \"w\" creates the file if it is missing and replaces it if it exists. write does not add a new line unless you include \n.

Mode \"x\" creates the file and fails if it already exists. Use that when overwriting would destroy work.

Example 1: Start here

On your machine, open the path with mode \"w\" inside a with block and call write.

lines = ["name=Meera\n", "city=Chennai\n"] # a list; the values stay in this order print("".join(lines)) # join the pieces into one text

Example 2: Join what write would send

write does not add a newline unless you include it.

parts = ["name=Asha", "city=Chennai"] # a list; the values stay in this order print("\n".join(parts) + "\n") # plus joins text; use str() for a number

Example 3: Append a line

Mode \"a\" on a real file adds to the end instead of replacing the file.

text = "name=Asha\n" # text text += "city=Chennai\n" # update the stored value print(text)

Example 4: Refuse to overwrite

Mode \"x\" raises an error when the file is already there. This check shows the same decision.

existing = {"notes.txt"} # a dictionary; each key has one value name = "notes.txt" # text if name in existing: # run the indented lines only when this is true print("already exists")
On your machine, open the path with mode \"w\" inside a with block and call write.
Call Now 81900 98289