Working with Files (Cheat Sheet)

Opening files examples...

afile = open("filename.txt")
afile.close()
afile = open("filename.txt", "w") // In read mode
afile.close()
afile = open("filename.txt", "r") // In write mode
afile.close()
afile = open("filename.txt"), "wb") // In binary write mode
afile.close()
afile = open("filename.txt"), "rb") // In binary read mode
afile.close()

Reading a file

The following code reads

file = open("file.txt", "r")
cont = file.read()
print(cont)
file.close()

Reading a number of characters

file = open("file.txt", "r") 
print(file.read(2))
print(file.read(3))
print(file.read(4))
file.close()

Example reading a file

The following reads chunks of four characters

file = open("file.txt", "r")
for i in range(21):
   print(file.read(4))
file.close()

Empty strings will be returned after the end will  be reached.

Reading lines from text file

The following codes reads a file into a list of string

file.open(file.txt)
print(file.readlines())
file.close()

Writing Files

A file will be created if it does not yet exist.
The content of an existing file will be deleted.

file.open("file.txt","w")
file.write("Write this text to the file")
file.close()

Tracking of bytes written

text = "Hello world"
file.open("file.txt","w")
amount_bytes = file.write(text)
print(amount_bytes)
file.close()

Using the "with" statement

with open("file.txt") as f:
   printf(f.read())