0% found this document useful (0 votes)
29 views

Day 8 Python

File handling in Python allows reading, writing, updating, and deleting files. The open() function opens a file and returns a file object. This object has methods like read(), readline(), write(), and close() to interact with the file. Files can be opened in read('r'), append('a'), write('w'), and create('x') modes. The file object returned by open() is used with these methods to read, write, and close the file. Files can also be deleted using the os.remove() function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Day 8 Python

File handling in Python allows reading, writing, updating, and deleting files. The open() function opens a file and returns a file object. This object has methods like read(), readline(), write(), and close() to interact with the file. Files can be opened in read('r'), append('a'), write('w'), and create('x') modes. The file object returned by open() is used with these methods to read, write, and close the file. Files can also be deleted using the os.remove() function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

TOT - Python Programming

Essentials
Day 8
File Handling
Allows the user to read, write, update, and delete files

open() - to open a file and returns a file object


read(), readline() - read content of the file
write() - to write to an existing file
close() - close the file
delete() - remove files
Open File
file = open("file.txt", [r,a,w,x])

● "r" - Read - Opens a file for reading, error if the file does not exist
● "a" - Append - Opens a file for appending, creates the file if it does not
exist
● "w" - Write - Opens a file for writing, creates the file if it does not exist
● "x" - Create - Creates the specified file, returns an error if the file exists

f = open("test.txt", mode='r', encoding='utf-8')


Read File
file = open("file.txt",”r”) #iterates every line
print(file.read()) f = open("data.txt", "r")
#print(file.read(5)) for x in f:
file.close() print(x)

#reads line by line #tokenizing words


print(file.readline()) with open("data.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
Write to a File
file = open("file.txt", "a") f = open("demofile3.txt", "w")
f.write("New Text") f.write("Woops! I have deleted the
content!")
f.close() f.close()

f = open("file.txt", "r") #open and read the file after the


appending:
print(f.read()) f = open("demofile3.txt", "r")
print(f.read())
Remove File
import os
os.remove("file.txt")

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

You might also like