my_file = open("test.txt", "w")
Mode | Description |
---|---|
'r' | Opens a file for reading (default) |
'w' | Opens a file for writing. Creates a new file if it does not exist |
'a' | Open for appending at the end of the file. Creates a new file if it does not exist. |
'b' | Opens in binary mode |
'+' | Opens a file for updating (reading & writing) |
When we are done with operations to the file, we need to properly close the file
The "close" method is used to close the file
It can be automatically done using "with" statement
f = open('output.txt', 'w')
# some operations here
f.close()
with open("data.txt", "a+") as f:
# some operations here
# now the file has been closed
with open("test.txt", "rb") as f: # Here we treat test.txt as a binary file - any file
# can be considered just a collection of bits
with open("test2.txt", "wb") as g: # Note the nested with statements
while True:
buf = f.read(1024) # The argument to read tells it to read a set number of
# bytes - each byte is an 8 bit (8 0's or 1's) words into the "buf" object,
# which is a string
if len(buf) == 0: # We're at the end
break
g.write(buf)
Example
Example