File Handling in Python
BASIC STUFF
# opening a file for reading
file = open('filename')
# opening a file for the specified mode
file = open('filename', 'mode')
# shorthand read/write with close
with open('filename', 'mode') as file:
statements
MODES OF FILE HANDLING
Action
Read Mode( "r" ): Default value. Opens a file for reading, error if the file does not exist.
Append Mode( "a" ): Opens a file for appending, creates the file if it does not exist.
Write Mode( "w" ): Opens a file for writing, creates the file if it does not exist.
Create Mode( "x" ): Creates the specified file, returns an error if the file exists.
Type of file
Text( "t" ): Default mode. Text mode.
Binary( "b" ): For binary files (eg. images)
READING FROM A FILE
# opening file to read
file = open("[Link]")
# reading the entire file at once
[Link]()
# only read first n characters of the file
[Link](n)
# read a single line from the file
[Link]()
# read all lines of the file as an array of strings
[Link]()
# close file after use
[Link]()
WRITING TO A FILE
# opening file to write
file = open('[Link]', 'a') # append content
file = open('[Link]', 'w') # overwrite content
file = open('[Link]', 'x') # create file if it doesn't exist
# write a whole string to a file
[Link]('Hello World!!')
# close file after use
[Link]()
DELETING FILES
# deleting a file
import os
[Link]('[Link]')
# check if file exists
import os
print([Link]('[Link]'))
# delete an empty folder
import os
[Link]('empty_folder')
SilicoFlare
silicoflare@[Link]
@silicoflare