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

File Handling

The document provides a comprehensive overview of file handling in Python, including how to open, read, write, and delete files. It details various file modes, methods like readline() and writelines(), and demonstrates file operations with code examples. Additionally, it explains file positions using tell() and seek() methods, along with creating and deleting files and folders.

Uploaded by

sambeing424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

File Handling

The document provides a comprehensive overview of file handling in Python, including how to open, read, write, and delete files. It details various file modes, methods like readline() and writelines(), and demonstrates file operations with code examples. Additionally, it explains file positions using tell() and seek() methods, along with creating and deleting files and folders.

Uploaded by

sambeing424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Python File

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!

Read only parts of the file:


► f = open("demofile.txt", "r")
print(f.read(5)) Hello
► f = open("demofile.txt", "r")
print(f.readline()) Hello! Welcome to demofile.txt
► print(f.readline()) This file is for testing purposes.

Loop through the file line by line:


► f = open("demofile.txt", "r")
for x in f: Hello! Welcome to demofile.txt
print(x) This file is for testing purposes.
► f.close() Good Luck!
Python File readline() Method

► Read the first line of the file ► Parameter Values


"demofile.txt":
► Parameter Description
► size Optional. The number of bytes
► f = open("demofile.txt", "r") from the line to return. Default
-1, which means the whole line.
► print(f.readline())

► Return only the five first bytes from the first


► The readline() method returns one line:
line from the file.

► 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:

► Use the hint parameter to limit the number of


► f = open("demofile.txt", "r") lines returned. If the total number of bytes
returned exceeds the specified number, no
► print(f.readlines()) more lines are returned.

► Do not return the next line if the total ► Syntax


number of returned bytes ar more
than 33: ► file.readlines(hint)

► f = open("demofile.txt", "r") ► hint Optional. If the number of bytes


returned exceed the hint number,
► print(f.readline(33)) no more lines will be returned.
Default value is -1, which means
all lines will be returned.
Write to a file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

f = open("demofile2.txt", "r") Hello! Welcome to demofile2.txt


This file is for testing purposes.
print(f.read())
Good Luck!Now the file has more content!

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the
content!")
f.close()

f = open("demofile3.txt", "r") Woops! I have deleted the content!


print(f.read())
Python File writelines() Method

► 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:

► Where the texts will be inserted


► f = open("demofile3.txt", "a") depends on the file mode and stream
position.
► f.writelines(["See you soon!", "Over
and out."])
► f.close() ► "a": The texts will be inserted at the
current file stream position, default
at the end of the file.
► #open and read the file after the
appending:
► "w": The file will be emptied before
► f = open("demofile3.txt", "r") the texts will be inserted at the
► print(f.read()) current file stream position, default
0.
Python File writelines() Method

► Syntax ► Inserting line breaks for each list item:


► file.writelines(list)
► f = open("demofile3.txt", "a")
► Parameter Values ► f.writelines(["\nSee you soon!", "\nOver
and out."])
► Parameter Description
► f.close()
► list The list of texts or byte
objects that will be
inserted.
► #open and read the file after the
appending:
► f = open("demofile3.txt", "r")
► print(f.read())
Create a New File

Use the open() method, with one of the following parameters:

"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

► >>> f.seek(0) # bring file cursor to initial position


0

► >>> f.seek(5) # Go to the 6th byte in the file

► >>> f.seek(-3, 2) # Go to the 3rd byte before the end


Writing in file
Writing the contents of string to the file
>>> f.write('This is a test\n')

Writing other objects to the file


>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
What will ‘demo.txt’ contain after
execution of this code?
file = open(‘demo.txt','w') demo.txt
file.write("This is the write command")
file.write("It allows us to write in a This is the write command
particular file")
It allows us to write in a particular file
file.close()
This will add this line

file = open(‘demo.txt','a')
file.write("This will add this line")
file.close()

You might also like