Python File Handling

File open

open()

opens the specified file.

open(filename, mode)

Mode

r read (default)

w write

a append

x creates a file, returns error if exists

Additional attributes

t text (default)

b binary

f = open("samplefile.txt", "wt") 

File write

write()

writes the content to the file.

f = open("samplefile.txt", "wt")
f.write("Sample File created successfully.\n")
f.write("Format - Text.")
f.close()

File read

read()

reads the entire content from the file.

f = open("samplefile.txt", "rt")print(f.read())
f.close()
Output
Sample File created successfully.
Format - Text.

readLine()

reads a single line from the file.

f = open("samplefile.txt", "rt")
print(f.readline())
f.close()
Output
Sample File created successfully.