0% found this document useful (0 votes)
1 views32 pages

Files in Python

Uploaded by

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

Files in Python

Uploaded by

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

FILES

Files in Python
•Files are named locations on disk to store related
information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk).

• Since Random Access Memory (RAM) is volatile


(which loses its data when the computer is turned
off), we use files for future use of the data by
permanently storing them.
FILES OBJECTS
FILE OBJECTS
• Python file object provides methods and
attributes to access and manipulate files.
• Using file objects, we can read or write in any
files.
• Whenever we open a file to perform any
operations on it, Python returns a file object.
• To create a file object in Python use the built-in
functions, such as open() and [Link]().
• IOError exception is raised when a file object is
misused, or file operation fails for an I/O-related
reason. For example, when you try to write to a
file when a file is opened in read-only mode.
Types of File Object

In Python, there are three different categories of


a file object:

1. Text files
2. Binary files
3. Raw files
Text files in Python
Text files don’t have any specific encoding and it can be
opened in normal text editor itself. Text files is used to
store character data or storing information in plain text
with no special formatting beyond basic fonts and font
styles.

Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Binary files in Python
Most of the files that we see in our computer system are called
binary files. Data is stored on a disk in the form of binary. Binary files
is used to store data like images or videos. The binary files are also
called buffered files. This file type is used for reading and writing
binary data.

Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
Raw files in Python
• A raw file is a collection of unprocessed data.
• It means the raw file has not been altered or
manipulated in any way by the computer.
• The raw files are also called unbuffered files,
and this file type is generally used as a low-level
building block for binary and text streams.
• Mostly, The raw file is not used.
• When we open these files, using the open()
function will return a FileIO object.
File Built-in
Function [ open() ]
Opening Files in Python

Python has a built-in open() function to open a file.


This function returns a file object, also called a
handle, as it is used to read or modify the file
accordingly.

EXAMPLE:

>>> f = open("[Link]“) # open file in current


directory
>>> f = open("C:/Python38/[Link]") #
specifying full path
Opening Files in Python Cont..

• We can specify the mode while opening a file. In


mode, we specify whether we want to read r,
write w or append a to the file.
• We can also specify if we want to open the file in
text mode or binary mode.
• The default is reading in text mode.
• In this mode, we get strings when reading from
the file.
• On the other hand, binary mode returns bytes
and this is the mode to be used when dealing
with non-text files like images or executable files.
Mode Description
r Opens a file for reading. (default)

w Opens a file for writing. Creates a new file if it does


not exist or truncates the file if it exists.

Opens a file for exclusive creation. If the file already


x exists, the operation fails.

Opens a file for appending at the end of the file


a without truncating it. Creates a new file if it does
not exist.
t Opens in text mode. (default)
b Opens in binary mode.

+ Opens a file for updating (reading and writing)


Closing Files in Python

• When we are done with performing operations on


the file, we need to properly close the file.
• Closing a file will free up the resources that were
tied with the file. It is done using the close() method
available in Python.
• Python has a garbage collector to clean up
unreferenced objects but we must not rely on it to
close the file.

Example:
f = open("[Link]", encoding = 'utf-8')
# perform file operations
[Link]()
Closing Files in Python Cont..
This method is not entirely safe. If an exception occurs when
we are performing some operation with the file, the code exits
without closing the file.
A safer way is to use a try...finally block.

try:
f = open("[Link]", encoding = 'utf-8')
# perform file operations
finally:
[Link]()

This way, we are guaranteeing that the file is properly closed


even if an exception is raised that causes program flow to stop.
Close File using ‘with’ statement

The best way to close a file is by using


the with statement. This ensures that the file is
closed when the block inside the with statement is
exited.
We don't need to explicitly call the close() method.
It is done internally.
Example:
with open("[Link]", encoding = 'utf-8') as f:
# perform file operations
File Built-in
Methods
Complete list of methods in text mode with a brief description:

Method Description

close() Closes an opened file. It has no effect if the file is already closed.

Separates the underlying binary buffer from the TextIOBase and


detach()
returns it.

fileno() Returns an integer number (file descriptor) of the file.

flush() Flushes the write buffer of the file stream.

isatty() Returns True if the file stream is interactive.

Reads at most n characters from the file. Reads till end of file if it
read(n)
is negative or None.

readable() Returns True if the file stream can be read from.


Method Description

Reads and returns one line from the file. Reads in


readline(n=-1)
at most n bytes if specified.

Reads and returns a list of lines from the file.


readlines(n=-1)
Reads in at most n bytes/characters if specified.

Changes the file position to offset bytes, in


seek(offset,from=SEEK_SET)
reference to from (start, current, end).
Returns True if the file stream supports random
seekable()
access.
tell() Returns the current file location.
Resizes the file stream to size bytes. If size is not
truncate(size=None)
specified, resizes to current location.

writable() Returns True if the file stream can be written to.

Writes the string s to the file and returns the


write(s)
number of characters written.
writelines(lines) Writes a list of lines to the file.
Reading Files in Python
•To read a file in Python, we must open the file in
reading r mode.
•There are various methods available for this purpose.
•There are three ways to read from a file.

1. read([n])
2. readline([n])
3. readlines()

Here n is the number of bytes to be read. If nothing is


passed to n, then the complete file is considered to be
read.
read(n)
•The read() method just outputs the entire file if
the number of bytes (n) is not given in the
argument.
•If you execute my_file.read(3), you will get back
the first three characters of the file.

Example:
my_file=open("[Link]","r")
print(my_file.read())
print(my_file.read(3))
readline(n)
•The readline(n) outputs at most n bytes of a single line
of a file.
•It does not read more than one line.
•The readline() method to read individual lines of a file.
•This method reads a file till the newline, including the
newline character.

Example:
my_file=open("[Link]","r")
print(my_file.readline())
print(my_file.readline(2))
readlines()
•The readlines() method maintains a list of each line
in the file which can be iterated using a for loop.
•The readlines() method returns a list of remaining
lines of the entire file.
•All these reading methods return empty values
when the end of file (EOF) is reached.

Example:
my_file=open("[Link]","r")
my_file.readlines()
write()

•In order to write into a file in Python, we need to


open it in write w, append a or exclusive
creation x mode.
•The write() method writes any string to an open file.
•It is important to note that Python strings can have
binary data and not just text.
•The write() method does not add a newline
character ('\n') to the end of the string. Writing a
string or sequence of bytes (for binary files) is done
using the write() method.
•This method returns the number of characters
written to the file.
Example and Methods to write to a file in Python:

Example 1:
with open("[Link]",'w',encoding = 'utf-8') as f:
[Link]("my first file\n")
[Link]("This file\n\n")
[Link]("contains three lines\n")

Example 2:
f = open("[Link]", mode='w')
[Link]("This is a object oriented language")
f = open("[Link]", mode='r')
print([Link]())
Methods to write to a file in Python:

1) write(string)
2) writelines(list)
write(string)
• write() method takes a string and writes it in the file.
• For storing data, with end of line character, we have to
add ‘\n’ character to the end of the string.
• For storing numeric value, we have to either convert it
into string using str() or write in quotes.

Example1:
f= open("[Link]", mode="w")
[Link]("Hello")
[Link]("\nHw r u?")
write(string) cont…

Example2:

f= open("[Link]", mode=“w")
a= int(input("Enter the value of a:"))
b= int(input("Enter the value of b:"))
c= a+b
[Link]("\nA =" + str(a))
[Link]("\nB =" + str(b))
[Link]("\nSum is =" + str(c))
[Link]()
writelines(list)
• writelines() method is used to write sequence data
types in a file(string, list and tuples etc).
• For storing data, with end of line character, we
have to add ‘\n’ character to the end of the string.

Example:
f= open("[Link]", mode="w")
list = ['apple\n','pineapple\n','grapes']
[Link](list)
tell()

This method is used to find current position of file pointer from beginning
of the file. Position starts from 0.

Syntax:
file_object.tell()

Example:

f = open("[Link]", mode='r')
print([Link]())
a = [Link](4)
print(a)
print([Link]())
b = [Link](2)
print(b)
print([Link]())
seek(position)
This method is used to move file pointer from one position to another
position from beginning of the file. Position starts from 0 and it must
be positive integer.

Syntax:
file_object.seek(position)

Example:
f = open("[Link]", mode='r')
print([Link]())
print([Link](4))
a = [Link]()
print(a)
print([Link](8))
b = [Link]()
print(b)
Renaming and Deleting Files
Python os module provides methods that help you perform file-
processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can
call any related functions.

1) The rename() Method:- The rename() method takes two


arguments, the current filename and the new filename.

Syntax
[Link](current_file_name, new_file_name)

Example
import os
[Link]( "[Link]", "[Link]" )
2) remove() Method

You can use the remove() method to delete files by


supplying the name of the file to be deleted as the
argument.

Syntax
[Link](file_name)

Example
import os
[Link]("[Link]")

You might also like