0% found this document useful (0 votes)
52 views13 pages

File Handling: Exercise: Create A Folder Named Myfiles. in The Folder, Using Notepad or Any Other Text Editor

The document discusses file handling in Python. It defines a file as a named location containing a sequence of bytes that allows permanently storing data. Python allows accessing the file system using the io module. There are two types of files - text files that are human-readable, and binary files that require specific programs to open. The document then covers opening files using the open() function, specifying modes like read ("r"), write ("w"), append ("a"), and read/write ("r+"). It also discusses closing files using close() or with statements. Methods like read(), readline(), and readlines() allow reading file contents.

Uploaded by

Debbie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views13 pages

File Handling: Exercise: Create A Folder Named Myfiles. in The Folder, Using Notepad or Any Other Text Editor

The document discusses file handling in Python. It defines a file as a named location containing a sequence of bytes that allows permanently storing data. Python allows accessing the file system using the io module. There are two types of files - text files that are human-readable, and binary files that require specific programs to open. The document then covers opening files using the open() function, specifying modes like read ("r"), write ("w"), append ("a"), and read/write ("r+"). It also discusses closing files using close() or with statements. Methods like read(), readline(), and readlines() allow reading file contents.

Uploaded by

Debbie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

BeyondPapers Workshop 1.

0 (Launch into Python Programming)

File Handling
A file is a named location on the memory containing a sequence of bytes. File Handling may be
useful in permanently storing data or information generated by a program, which would
otherwise be unavailable after the program has finished running, since they are only stored
temporarily in the volatile RAM. Luckily, Python has the capability to access your device file
system using the io module. However, being the default module for handling I/O functions,
you do not need to literally import the io module or any other module, while handling files.

Python supports two types of file. They include:


 Text files: These kinds of file have no specific encoding, and are therefore human-readable.
They can be opened with a normal text editor. Examples include: .txt, .html, .xml, .css,
.py, .csv, .ini files etc.
 Binary files: This is the form in which most files come. They are machine-readable, and
opening them in a text-editor, leaves the human eye useless, as they are not human-
readable. This is because binary files are encoded. For these kinds of files, specific programs
are needed to open them. Examples include: .jpg, .png, .pdf, .doc, .ppt, .3gp, .mp4, .exe,
.class, .zip, .iso files etc.

Exercise: Create a folder named MyFiles. In the folder, using Notepad or any other text editor,
create a text file (with the .txt file extension), and type in Hello World. Name the file Hello.txt.
It is possible to create a text file using WPS Office. Simply click on the + button, and click New
Memo from the list of options, then save your file in the said location with the .txt extension.
Ensure the .txt extension is not repeated in your file name.

Now, in the same folder, create a python program of any name of your choice, and write the
following code:
MyHello = open("Hello.txt", "r")
x = MyHello.read()

print(x)

Boom! The output should be:


Hello World
>>>

1 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

What has just happened? With Python we have just accessed the file Hello.txt and read its
content! How did we do that? First we need to open the file in question.

Opening a File
To open a file, use the open() function. The open() function creates a file object (or stream),
and the variable to which the it is assigned to becomes the file handler for the file on the
operating system. The open() function takes two arguments. The syntax is:

open(file, mode)

file refers to the address of the file to be handled. If the file to be opened is located on the
same directory as the program opening it, it may be enough to write just the name (with the
file extension, for example, "home.html" or "Hello.txt"). However, if the file is located
elsewhere, you may need to specify the proper relative path or an absolute path.

mode refers to the way we want to open the file, and what actions can be done on the file. In
other words, it defines the behaviour of the file handler, and what methods can be used on it.
In the above example, Hello.txt is the file (or address of the file) to be opened, and r
represents the mode with which we want to open the file. Opening a file with the r mode
means we want to open the file for reading. The open() function therefore returns a read-only
file object representing the file on the disk, and as such we cannot write to or edit the file. This
is the default mode, which means, we could have opened the file as:
open("Hello.txt")

There are other modes with which we can open a file. Below is a list of all the modes:
Mode Purpose Behaviour
r for reading content only This is default.
You cannot edit the file.
w for writing new content only Creates a new file.
Overwrites, if a file with the same name
already exists. (Clears initial contents.)
a for appending (or writing more) content Creates a new file, if the file does not
only exist.
x for creating and writing to files Raises an exception if the file already
exists.

It is also possible to open a file for multiple purposes:

2 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

r+ for reading and writing Raises an exception if the file does not
exist.
w+ For reading and writing Creates a new file.
Overwrites, if a file with the same name
already exists. (Clears initial contents.)
a+ For reading and appending Creates a new file, if the file does not
exist.
x+ For creating, writing and reading Raises an exception if the file already
exists.

In Python, files can be handled in either text or binary formats. To specify which format you
want to work with, you add "t" (text) or "b" (binary) to the mode. The default is "t".
open("Hello.txt") therefore means open("Hello.txt", "rt"). If for example, a file is to be opened
as read and write in binary format, the mode will be written as "rb+" or "wb+".

Closing a File
It is a good practice to close files, after all operations have been carried out on the file. Closing
a file will free up resources that were tied to the file, including memory, battery life etc.
Sometimes, due to buffering, certain changes made to a file may not be shown, until the file
handler is closed.

To close a file, use the close() method on the file handler:


MyHello = open("Hello.txt", "r")
x = MyHello.read()
print(x)

MyHello.close()

The with statement can also be used to close a file. It automatically closes the file when the
block of code is finished executing. We do not need to explicitly call the close() method.

with open("Hello.txt") as f:
content = f.read()
print(content)

The file is automatically closed after all codes for working on the file in the with statement
have been executed.

3 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Reading a File
To read the contents of a file, use the read() method.

Exercise: Create a file, MyLines.txt. Write the following in it, and save:

BeyondPapers Workshop 1.0 hosts training in Python Programming.

The workshop is for beginners in programming.

It’s been fun learning Python here.

To read the contents of MyLines.txt, write a program with the following code, in the same
folder:
File = open("MyLines.txt")

Lines = File.read()
print(Lines)

File.close()

The output should be:


BeyondPapers Workshop 1.0 hosts training in Python Programming.
The workshop is for beginners in programming.
It’s been fun learning Python here.
>>>

When opening a file for reading, if the file to be read does not exist, an exception will be
raised.

The read() method reads the whole content of a file. The read() method can also take an
argument n, used to read only parts of a file. It tells the file handler to return only the first n
bytes or characters. If a negative value is given, it will return the rest of the file content.

File = open("MyLines.txt")

Lines = File.read(12)
print(Lines) # Prints "BeyondPapers"

File.close()
4 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Lines are separated by the line break \n character. To read the lines of a file one after the
other, use the readline() method. The readline() method can also take an argument n, to read
the first n characters from the line. A negative value of n returns the whole line.

# To read the first two lines of MyLines.txt, apply the readline() method twice.

File = open("MyLines.txt")

Line1 = File.readline()
print(Line1)

Line2 = File.readline()
print(Line2)

# To read only the first 4 characters on the third line:

Line3 = File.readline(4)
print(Line3)

File.close()

Output is:
BeyondPapers Workshop 1.0 hosts training in Python Programming.

The workshop is for beginners in programming.

It’s
>>>

The readline() method, reads each line of a file one at a time, and appends the line break \n
character to each line (except the last line). This implies that we can actually loop through the
whole lines of the file:
File = open("MyLines.txt")
while True:
Line = File.readline()
if len(Line) > 0: print(Line)
else: break

5 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

File.close()

While both gives the same result, it may be more economical to write:
File = open("MyLines.txt")
for i in File: print(i)
File.close()

The output in both cases is:


BeyondPapers Workshop 1.0 hosts training in Python Programming.

The workshop is for beginners in programming.

It’s been fun learning Python here.


>>>

The readlines() method can be used to return a list of the lines instead. When the argument n
is passed, the readline() method returns the lines up to the next complete line after n
characters. When a negative n is supplied, the whole lines are read.

File = open("MyLines.txt")
AllLines = File.readlines()
print(AllLines)
File.close()

Writing to a File
Just like files can be read, files can as well be written to. This is done by opening a file as a
writable file and then using the write() method on it. To open a writable file, open it with the
w mode. Opening a file with "w" overwrites any previous file with the same name in the
directory – that is it deletes the contents of the file, leaving it empty, until it is written to.

Here we will be creating a new file, LetsWrite.txt, and writing some content to it.
x = open("LetsWrite.txt", "w")

x.write("Something has been written to me!")


x.close()

# To confirm our content has been written:


6 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

x = open("LetsWrite.txt", "r")
print(x.read()) # Prints # "Something has been written to me!"
x.close()

The writelines() method can be used to write a list of strings to a file:


e = open("StudentEmails.txt", "w")

List = ["[email protected]\n", "[email protected]\n", "[email protected]"]


e.writelines(List)
e.close()

# To confirm our content has been written:

e = open("StudentEmails.txt", "r")
print(e.read())
e.close()

Appending a File
When you append a file, you write more contents to it, without altering the initial content. To
append a file, open it in the append mode (that is, with mode "a"), and write your contents to
it. Opening a file with mode "a" creates a new file, if it does not already exist.

# Let's assume I have earlier written some content to my Notebook, or it already has some.

Note = open("Notebook.txt", "w")


Note.write("This is my first note.\n\n")
Note.close()

# Now let me append a new note:

Note = open("Notebook.txt", "a")


Note.write("Hurray! I have added one more note.")
Note.close()

# Now let's check my note:

7 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Notes = open("Notebook.txt", "r").read()


print(Notes)

You can for example use the append mode to append the items of a list to a file:
# My teacher writes this on the board:

Topic = "MY STORE"


List = ["Hacksaw", "Drill", "Rule"]

# I need to add it to my previous notes:

Note = open("Notebook.txt", "a") # I opened it in append mode to avoid losing my old notes.
Note.write("\n\n%s" %Topic)

for i in List:
Note.write("\n%s" %i)

Note.close() # I have to close my note, so I can free up space, and make it usable by other
programs.

# Now let's check my note:

Notes = open("Notebook.txt", "r").read()


print(Notes)

Output will be:


This is my first note.

Hurray! I have added one more note.

MY STORE
Hacksaw
Drill
Rule
>>>

Seeking in a File

8 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Earlier in this tutorial, we used the readline() method, and observed that the file handler
automatically does not repeat line 1, when it is repeatedly used on the file object. This is
possible because the file handler uses a location pointer to ‘mark off’ its last position. When a
file is just opened in read mode, the location of the file handler is 0, and when an action, such
as read() is done on a file object, the file handler is moved to the end of the file. Attempting to
read the file once more will return a null string. Opening a file in append mode will place the
file handler at the end of the file, allowing us to write more content to the end of the file,
without altering the previous.

Sometimes, we may need to read the content of a file randomly or describe a specific position
for the file handler in a file stream. We use the seek() method to achieve this. The syntax for
the seek() method is:

seek(offset, location)

While location specifies an absolute value, offset specifies the position of a file handler relative
to location – that is, it specifies the number of bytes from or to location. For example:
# I need to recover parts of my note.

Note = open("Notebook.txt", "r")

# To set the file handler to the beginning of the file:


Note.seek(0)
print(Note.readline())

# To set the file handler 11 bytes from the beginning of the file, and read the first 5 bytes:
Note.seek(11)
print(Note.read(5))

# To set the file handler to the current position of the file handler:
# Note that nonzero offsets can not be used, when location = 1 or 2, while working with texts.
# It is only possible when the file is opened in binary mode. ("rb" for instance)
Note.seek(0, 1)
print(Note.readline())

# To set the file handler to the end of the file:


Note.seek(0, 2)
print(Note.read()) # Will return a null string "".

9 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Output will be:


This is my first note.

first
note.

>>>

While the seek() method returns the newly set position of the file hander, the tell() method
returns the current position of the file handler:
Note = open("Notebook.txt", "a")
# Appending mode places the file handler at the end of the file.

print(Note.tell()) # Prints 95

The seekable() method can be used to check if the seek() method can be used on a file object –
returns True or False.

Editing a File
To edit a file, simply open the file in read mode, and read it to a variable. You then perform
operations on the variable and write it back to the file. You may also loop through each line or
word separately, and edit the intended item.
The example below shows how to replace all instances of "hate" with "like":

Hatelist = """I HATE snakes.


I hate monkeys.
I hate dogs.
I hate cats.
I LIKE pets."""
Hate = open("MyHateList.txt", "w")
Hate.write(Hatelist)
Hate.close()

# The above code is just to create the file MyHateList.txt, and write the intended content.

10 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

# Now, to edit its content:

# First read the file.


Hate = open("MyHateList.txt", "r")
Hatelist = Hate.read()
Hate.close()

# Edit the content.


Likelist = Hatelist.replace("hate", "like")

# Write back the new content.


Like = open("MyHateList.txt", "w+") # Deletes the previous content while opening. Notice the
use of "w+" mode.
Like.write(Likelist) # Writes the edited content. The file handler is left at the end of the file.

# Confirm the content. We do not need to reopen the file, since we opened the file in read
and write mode.
Like.seek(0) # Returns the file handler to the beginning of the file.
print(Like.read())

Like.close()

Output is:
I HATE snakes.
I like monkeys.
I like dogs.
I like cats.
I LIKE pets.
>>>

Copying a File
To copy a file or its content, simply open the file in read mode, read the file and write it to
your new file. Here, we will be copying a file from a main directory to a sub-directory. Create a
folder named Parent, and create another folder named Child inside of Parent.
Inside Parent, create a program, and write the following:

Old = open("old.txt","w")
11 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Old.write("My content will soon be copied to a new file.")


Old.close

# All we have done up there is to create the old file we want to copy

# Now to copy a file:


Old = open("old.txt") # Opens in read mode
OldContent = Old.read() # Copies the content of old.txt temporarily.
Old.close()

New = open("Child/new.txt", "w") # Creates a file for writing inside the folder Child.
New.write(OldContent) # Writes the old content into new.txt
New.close() # You may need to close your file, for changes to be seen.

print("File copied successfully!")

Moving a File
The process of moving a file is similar. You just need to create both files with the same name in
different folders, and delete the old one.

The name attribute returns the name of the file:


Old = open("old.txt")
print(Old.name)

Deleting a File
Python does not have a built-in method to delete files, but you can import the OS module, and
use its remove() function:
import os
os.remove("old.txt")

The remove() function will raise an exception if the file does not exist. To avoid this, check if
the file exists first:
import os
os.remove("older.txt") if os.path.exists("older.txt") else print("File not found!")

12 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

To delete only the content of a file, while preserving the file itself, it is enough to open it in
write mode.

Working with Binary Files:


Binary files are stored in bytes (sequences of bits, representing a single character or a number
from 0 - 255). Machines work with binary files directly, because bytes are machine-readable.
On the other hand, they are not readable to humans. A way of writing binary files is by
working with a binary file is the binary mode. Files are then encoded while writing, and
decoded while reading.

file = open("binfile.bin","wb")

s = "Hello World"
arr = s.encode("utf-8") # Encodes the string in UTF-8 characters as bytes.

print("Content shown:", arr)


file.write(arr)
file.close()

print("The readable form: ", arr.decode("utf-8")) # Must be decoded to become readable.

# To get the actual bytes written


print("The actual bytes:", end=" ")
for byte in arr:
print(byte, end=" ")

Output should be:


Content shown: b'Hello World'
The readable form: Hello World
The actual bytes: 72 101 108 108 111 32 87 111 114 108 100
>>>

13 |B e y on d P a p e r s

You might also like