Python open() function
Open a file for reading or writing.
Syntax
open(file, mode="r", encoding=None, newline=None)
Use it in a with block so the file is closed automatically. Common modes: "r" read, "w" write (wipes the file), "a" append, plus "b" for binary. Always pass encoding="utf-8" for text.
Parameters
| file | the file name or path |
| mode | r, w, a (add b for binary) |
| encoding | use "utf-8" for text |
| newline | use "" when writing CSV |
Return value
a file object
Example
Code
with open("demo.txt", "w", encoding="utf-8") as f: f.write("line one\nline two\n") with open("demo.txt", encoding="utf-8") as f: for line in f: print(line.strip()) with open("demo.txt", "a", encoding="utf-8") as f: f.write("line three\n") print(open("demo.txt", encoding="utf-8").read().count("\n"), "lines")
Output
line one line two 3 lines
Good to know. Mode
"w" empties the file first. Use "a" to add to it.Related
Learn it step by step in the free lesson Files, with exercises that check your answers.