File Operations

I LOVE DOING THIS :)

File Input and Output in Python really helps us to read - write and store persistent data

open(file_name, access_mode)

read(byte_count)

write(data)

close()

os.rename()

os.delete()

write() - If the file doesn't exists then it gets created and if it exists it will be over-written

>>> file = open("test.txt","w")
>>> file
<_io.TextIOWrapper name='test.txt' mode='w' encoding='UTF-8'>

TypeError: write() argument must be str, not int

#!/opt/python3

file = open("test.txt","w")

for count in range(0,100):
	file.write(str(count) + "\n")

file.close()

Incase, if we wanna append() , we can simply use the append call and its descriptor

#!/opt/python3

file = open("test.txt","a")

for count in range(100,200):
	file.write(str(count) + "\n")

file.close()

To read the file we can use the read syscall

#!/opt/python3

file = open("test.txt","r")

for line in file.readlines():
    print(line.strip())

line.strip() will automatically append the "\n" new line character in the end

Have a read !

Exercise Question

  • Read /var/log/messages

  • Find all the logs in it which pertain to USB and grep them out selectively

#!/opt/python3

import sys

logfile = open(sys.argv[1])

for line in logfile.readlines():
	if line.lower().find("usb") != 1:
		print(line)

print("Done !")

Last updated