How to read, write and append to file



Reading and writing to a file is quite straight forward, first thing we need to do is open the file.

Open the file

f = open("myfile.txt", "r")  # Open the file in read mode

- The path can point to a local file or it could be an absolute path

- The file can be open in different modes, I will only mention the most used, check:

 r    open the file in read mode

rb open the file for reading binary format

r+ open the file both in read and write mode

w  open the file in write mode, overwrite the file if exists

 a   open the file in append mode. If the file doesn't exist it creates it and if it exists, the file pointer is set to the end of file.

Write to the file

f = open("myfile.txt", "w")  # Open the file in write mode
f.write("Hello \nWorld!")
f.close()

Read the file

f = open("myfile.txt", "r")  # Open the file in read mode
print(f.read())  # .read() will print all file content
f.close()  # It's good practice to close the file when you finish

Output: 
Hello
World!

# We could also use .readlines() and get an array with the lines
f = open("myfile.txt", "r")  # Open the file in read mode
print(f.read())
f.close()
Output:  ['Hello\n', 'World!']

# We could also use .read(5) to read the first 5 characters
f = open("myfile.txt", "r")  # Open the file in read mode
print(f.read(5))
f.close()
Output:  Hello

Append to the file

f = open("myfile.txt", "a")  # Open the file in append mode
# Assumming we have an existing file with 2 lines 'Hello\n' and 'World!'
f.write("\nExtra line")
f.close()  # It's good practice to close the file when you finish

f = open("myfile.txt", "r")
print(f.readlines())
f.close()

Output: ['Hello\n', 'World!\n', 'Extra line']

 

Leave a comment

You have to wait to comment again. Wait Time: