{"id":"writing-files-create","slug":"create","title":"Creating and writing a file","text":"Programs also save data to files: results to keep for later, a report for a person to read, or data for another program to use. Writing uses the same `open` function as reading, with a second argument, the **mode**. The mode `\"w\"` opens the file for **writing**:\n\n```python\nwith open(\"greeting.txt\", \"w\") as file:\n    file.write(\"Hello, file!\\n\")\n    file.write(\"This is the second line.\\n\")\n\nwith open(\"greeting.txt\") as file:\n    print(file.read())\n```\n\n```output\nHello, file!\nThis is the second line.\n```\n\n- `open(\"greeting.txt\", \"w\")` creates the file in the program's folder.\n- The file handle's method **`write`** writes a string into the file.\n- The second `with` block opens the file for reading (with no mode, `open` reads) only to show what the program wrote. On this site, the tests of a task look at the files your program leaves in its folder.\n\n### write doesn't add line breaks\n\n`print` ends each line for you, but `write` writes exactly the string it gets and nothing more. Line breaks are up to you: end each line with `\\n`. Forget them, and the lines run together:\n\n```python\nwith open(\"numbers.txt\", \"w\") as file:\n    file.write(\"one\")\n    file.write(\"two\\n\")\n    file.write(\"three\\n\")\n\nwith open(\"numbers.txt\") as file:\n    print(file.read())\n```\n\n```output\nonetwo\nthree\n```\n\n### Only strings\n\n`write` takes exactly one string. Give it a number and Python stops:\n\n```python\npoints = 42\nwith open(\"points.txt\", \"w\") as file:\n    file.write(points)\n```\n\n```crash\nTraceback (most recent call last):\n  File \"main.py\", line 3, in <module>\n    file.write(points)\n    ~~~~~~~~~~^^^^^^^^\nTypeError: write() argument must be str, not int\n```\n\nTurn the number into a string first. An f-string is the handiest way, and it adds the line break at the same time: `file.write(f\"{points}\\n\")`. It works just as well for a line with several values, such as `file.write(f\"{name} scored {points}\\n\")`.\n\n### \"w\" starts from scratch\n\nIf a file with that name already exists, opening it with `\"w\"` empties it first. Everything that was in it is gone, without any warning:\n\n```python\nwith open(\"status.txt\", \"w\") as file:\n    file.write(\"Version 1\\n\")\n\nwith open(\"status.txt\", \"w\") as file:\n    file.write(\"Version 2\\n\")\n\nwith open(\"status.txt\") as file:\n    print(file.read())\n```\n\n```output\nVersion 2\n```\n\nThat's what you want when a program writes a fresh result every time it runs, but think twice about the name you give `open` with `\"w\"`: a typo can wipe out the wrong file.\n","task":"Fill in the blanks so the program creates the file `todo.txt` with these two lines in it:\n\n```text\nBuy milk\nFix the bike\n```\n","kind":"fill","seed":"with open(\"todo.txt\", [[\"w\"‖'w']]) as file:\n    file.[[write]](\"Buy milk\\n\")\n    file.write(\"Fix the bike\\n\")\n","solution":"with open(\"todo.txt\", \"w\") as file:\n    file.write(\"Buy milk\\n\")\n    file.write(\"Fix the bike\\n\")\n","hints":["The second argument of `open` is the mode, as a string. The mode for writing is the letter w.","The first blank is `\"w\"`, with its quotes. The second is the method that writes a string into the file, the same as on the line below it."],"tests":[{"name":"Files","stdin":"","writes":{"todo.txt":"Buy milk\nFix the bike\n"},"expect":"","hidden":false}],"require":[],"forbid":[],"more":[{"task":"Write a program that asks for the user's name and favorite color and saves them to the file `profile.txt`, as two lines like `Name: Ada` and `Color: green`. Then it prints `Saved profile.txt`.\n\nA run looks like this:\n\n```\nYour name: Ada\nYour favorite color: green\nSaved profile.txt\n```\n\nand leaves this in `profile.txt`:\n\n```text\nName: Ada\nColor: green\n```\n","kind":"code","seed":"name = input(\"Your name: \")\ncolor = input(\"Your favorite color: \")\n","solution":"name = input(\"Your name: \")\ncolor = input(\"Your favorite color: \")\nwith open(\"profile.txt\", \"w\") as file:\n    file.write(f\"Name: {name}\\n\")\n    file.write(f\"Color: {color}\\n\")\nprint(\"Saved profile.txt\")\n","hints":["Open `profile.txt` with the mode `\"w\"` and write each line with `file.write`.","An f-string builds each line, and the line ends with `\\n`: `file.write(f\"Name: {name}\\n\")`.","Print the message after the `with` block, when the file is written and closed."],"tests":[{"name":"Test 1","stdin":"Ada\ngreen\n","writes":{"profile.txt":"Name: Ada\nColor: green\n"},"expect":"Your name: Ada\nYour favorite color: green\nSaved profile.txt","hidden":false},{"name":"Test 2","stdin":"Linus\ndark blue\n","writes":{"profile.txt":"Name: Linus\nColor: dark blue\n"},"expect":"Your name: Linus\nYour favorite color: dark blue\nSaved profile.txt","hidden":true}],"require":[],"forbid":[]},{"task":"What does this program print? Type each line it prints.\n","kind":"predict","seed":"with open(\"log.txt\", \"w\") as file:\n    file.write(\"start\")\n    file.write(\"stop\\n\")\n    file.write(f\"{2 * 3}\\n\")\n\nwith open(\"log.txt\") as file:\n    for line in file:\n        print(line.strip())\n","solution":"with open(\"log.txt\", \"w\") as file:\n    file.write(\"start\")\n    file.write(\"stop\\n\")\n    file.write(f\"{2 * 3}\\n\")\n\nwith open(\"log.txt\") as file:\n    for line in file:\n        print(line.strip())\n","hints":["`write` doesn't add line breaks: the first two strings end up on the same line of the file.","The f-string calculates `2 * 3` and writes the result, followed by a line break."],"tests":[{"name":"Output","stdin":"","expect":"startstop\n6","hidden":false}],"require":[],"forbid":[],"lines":["startstop","6"]}]}