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("hello.txt")
# reading the entire file at once
file.read()
# only read first n characters of the file
file.read(n)
# read a single line from the file
file.readline()
# read all lines of the file as an array of strings
file.readlines()
# close file after use
file.close()
WRITING TO A FILE
# opening file to write
file = open('hello.txt', 'a') # append content
file = open('hello.txt', 'w') # overwrite content
file = open('hello.txt', 'x') # create file if it doesn't exist
# write a whole string to a file
file.write('Hello World!!')
# close file after use
file.close()
DELETING FILES
# deleting a file
import os
os.remove('hello.txt')
# check if file exists
import os
print(os.path.exists('hello.txt'))
# delete an empty folder
import os
os.rmdir('empty_folder')
SilicoFlare
[email protected]
@silicoflare