open()
The built-in function that opens a file by name and returns a file object, for reading by default or for writing or appending.
In more detail
open("notes.txt", "w") creates or empties the file; open("notes.txt") reads it. A relative name is looked up in the current working directory, so a program run from another folder may not find its files. Pass encoding="utf-8" to get the same result on every system.
Example
with open("out.txt", "w", encoding="utf-8") as f:
f.write("hi\n")Related terms
- file object — The object returned by open() that you read from or write to, and close when finished.
- file mode — The second argument to open(), which says how the file will be used: "r" read, "w" write from scratch, "a" append, with "b" added for bytes.
- with statement — A statement that sets something up, runs a block, and guarantees the matching clean-up afterwards, most often closing a file.
- character encoding — The rule for turning text characters into bytes and back, such as UTF-8.
Taught in
- What A Program Really Is — Hands-on Python: Complete Video Course & Book
- Editors, IDEs And Shells — Hands-on Python: Complete Video Course & Book
- Installing Python On Windows — Hands-on Python: Complete Video Course & Book
- Files: Writing And Reading — Hands-on Python: Complete Video Course & Book
- Windows And Mac Specifics — Hands-on Python: Complete Video Course & Book
- Paths And Files The Modern Way — Hands-on Python: Complete Video Course & Book
- The Class That Shared One List — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Import Variants, dir() And sys.path — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Your Own Modules And Packages — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Modules Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exceptions Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Introspection: hasattr, __name__, __module__ And __bases__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Streams, Handles And Open Modes — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- read, readline, errno And bytearray — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Mock, Review And Exam Day — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep