File Handling
File Handling
Handling
What is a file?
How a file operation takes place in python
► Open a file
Open a file
f = open("demofile.txt")
f = open("demofile.txt", "rt")
f = open("C:/Python33/README.txt")
f = open("test.txt", mode='r', encoding='utf-8’)
► Modes:
► '+' Open a file for updating (reading and writing)
► r, rb, r+, rb+, w, wb, w+, wb+, a, ab, a+, ab+
Read a file
► demofile.txt Output
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
► f = open("demofile.txt", "r") Hello! Welcome to demofile.txt
print(f.read()) This file is for testing purposes.
Good Luck!
► f = open("demofile.txt", "r")
► You can also specify how many bytes
from the line to return, by using the ► print(f.readline(5))
size parameter.
► O/p: Hello
► Syntax
► file.readline(size)
Python File readlines() Method
► Return all lines in the file, as a list ► The readlines() method returns a list
where each line is an item in the list containing each line in the file as a list item.
object:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the
content!")
f.close()
► Open the file with "a" for appending, ► The writelines() method writes the
then add a list of texts to append to items of a list to the file.
the file:
"x" - Create - will create a file, returns an error if the file exist
f = open("myfile.txt", "x")
"a" - Append - will create a file if the specified file does not exist
f = open("myfile.txt", “a")
"w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", “w")
Delete a File/Folder
► File ► Folder
► import os ► import os
os.remove("demofile.txt") os.rmdir("myfolder")
► import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Python File Methods
File Positions
► The tell() method tells you the current position within the file; in other
words, the next read or write will occur at that many bytes from the
beginning of the file.
► The seek(offset[, from]) method changes the current file position. The offset
argument indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved.
► If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position and if
it is set to 2 then the end of the file would be taken as the reference
position.
File Positions
► >>> f.tell() # get the current file position
56
file = open(‘demo.txt','a')
file.write("This will add this line")
file.close()