You are on page 1of 1

File IO

# How to read text files try:


# Syntax: F = open("file1.txt")
# ID = open( file_path , mode), mode: print(F.read())
r, w, a | b except:
raise
finally:
File1.text: F.close()

Hello World # With statement [Alternative for try-


finally]: Pythonic Style
This is me!
with open("file1.txt") as FI1: #
Automatically close the file after
execution
print(FI1.readlines())
# ID = open("File1.txt", "w")
# ID.close()

Read all text ------------------------


F1 = open("File1.txt", 'r')
Str = F1.read()
print(Str + '\n\n')
F1.close()

Read based on number of bytes --------

F2 = open("File1.txt", 'r')
Str1 = F2.read(4)
Str2 = F2.read(5)
print(Str1 + '| |' + Str2)
Str3 = F2.read()
Str4 = F2.read()

print(Str3)
print(Str4) # Empty String, reading
cursor in end of the file
F2.close()

Read Lines ------------------------

F1 = open("File1.txt",'r')
print(F1.readlines()) # Output: List (of
each line)
F1.close()

Writing Files ----------------------

F2 = open("File1.txt", 'a') # if 'w',


contents will be Overwrite (deleted)
F2.write("Line 4\n")
print(F2.write("Line 5\n")) # return no
of written bytes
F2.close()

print(open("file1.txt").read())

Python course

You might also like