0% found this document useful (0 votes)
8 views43 pages

File IO

The document provides an overview of file handling in Python, including the definition of files, types of files (text and binary), and various file operations such as reading, writing, and appending. It highlights the advantages of file handling in Python, such as versatility, flexibility, user-friendliness, and cross-platform compatibility. Additionally, it discusses the use of the os module for interacting with the operating system and managing files and directories.

Uploaded by

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

File IO

The document provides an overview of file handling in Python, including the definition of files, types of files (text and binary), and various file operations such as reading, writing, and appending. It highlights the advantages of file handling in Python, such as versatility, flexibility, user-friendliness, and cross-platform compatibility. Additionally, it discusses the use of the os module for interacting with the operating system and managing files and directories.

Uploaded by

shawn1603m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Pyhton Files

Ms. Sangeeta
Assistant Professor
CSE Department
CENTRAL UNIVERSITY OF HARYANA
Content
• Files
• File Handling
• Advantages of File Handling
• Types of Files
• File Operations
• Pythonic Way using “With”
• os and sys module
• Formatted Files(csv files)
File
A file is a named location on disk to store related information. We can access the
stored information (non-volatile) after the program termination.
File
A file is a named location on disk to store related information. We can access the
stored information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text
or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character. Python executes the code line by line. So, it works
in one line and then asks the interpreter to start the new line again. This is a
continuous process in Python.
File
A file is a named location on disk to store related information. We can access the
stored information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text
or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character. Python executes the code line by line. So, it works
in one line and then asks the interpreter to start the new line again. This is a
continuous process in Python.
Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on
the console since the memory is volatile, it is impossible to recover the
programmatically generated data again and again.
File Handling
Python supports the file-handling process. Till now, we were taking the input from
the console and writing it back to the console to interact with the user. Users can
easily handle the files, like read and write the files in Python. In another
programming language, the file-handling process is lengthy and complicated. But
we know Python is an easy programming language. So, like other things, file
handling is also effortless and short in Python.
File handling in Python is a powerful and versatile tool that can be used to perform
a wide range of operations.
Advantages of File Handling in Python
• Versatility : File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
Advantages of File Handling in Python
• Versatility : File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
• Flexibility : File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files , etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
Advantages of File Handling in Python
• Versatility : File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
• Flexibility : File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files , etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
• User-friendly : Python provides a user-friendly interface for file handling, making
it easy to create, read, and manipulate files.
Advantages of File Handling in Python
• Versatility : File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
• Flexibility : File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files , etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
• User-friendly : Python provides a user-friendly interface for file handling, making
it easy to create, read, and manipulate files.
• Cross-platform : Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
Types of Files
• Text files are used for saving text and they are almost always human-readable.
Examples include documents, source codes (for example, Python programs),
HTML pages (including style and script files), and anything else made with text
editors like Notepad.
Types of Files
• Text files are used for saving text and they are almost always human-readable.
Examples include documents, source codes (for example, Python programs),
HTML pages (including style and script files), and anything else made with text
editors like Notepad.
Note-generally, this does not include documents written with Microsoft Word and
other text processors.
For text files, the buffer is usually flushed whenever a new line is started.
Types of Files
• Text files are used for saving text and they are almost always human-readable.
Examples include documents, source codes (for example, Python programs),
HTML pages (including style and script files), and anything else made with text
editors like Notepad.
Note-generally, this does not include documents written with Microsoft Word and
other text processors.
For text files, the buffer is usually flushed whenever a new line is started.
• Binary files are closer to the way the data is stored in the computer's working
memory. They are typically used for various media files (images, movies, music,
etc), data collections (for example, ZIP, RAR, and similar archives), and some
formated documents (for example, older versions of Word documents).
Character Meaning
‘t’ Text
‘b’ Binary

So, the mode "t" means:


Open the file in text mode. It is the default mode of file. If we don’t specify any
mode then it will works in text mode.
Similarly, "b" means:
Open the file for reading in binary mode. If it doesn't exist, a FileNotFoundError
exception is raised.
File Operations
A file operation starts with the file opening. At first, open the File then Python will
start the operation. File opening is done with the open() function in Python. This
function will accepts two arguments, file name and access mode in which the file is
accessed. When we use the open() function, that time we must be specified the mode
for which the File is opening. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
file object = open(<file-name>, <access-mode>)
Example-
F=open(“[Link]”, “r”)
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some
data, then it will be overridden but if the file is not present then it creates the file
as well.
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some
data, then it will be overridden but if the file is not present then it creates the file
as well.
• a: open an existing file for append operation. It won’t override existing data.
• r+: To read and write data into the file. This mode does not override the existing
data, but you can modify the data starting from the beginning of the file.
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some
data, then it will be overridden but if the file is not present then it creates the file
as well.
• a: open an existing file for append operation. It won’t override existing data.
• r+: To read and write data into the file. This mode does not override the existing
data, but you can modify the data starting from the beginning of the file.
• w+: To write and read data. It overwrites the previous file if one exists, it will
truncate the file to zero length or create a file if it does not exist.
• a+: To append and read data from the file. It won’t override existing data.
• rb: It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some
data, then it will be overridden but if the file is not present then it creates the file
as well.
• a: open an existing file for append operation. It won’t override existing data.
• r+: To read and write data into the file. This mode does not override the existing
data, but you can modify the data starting from the beginning of the file.
• w+: To write and read data. It overwrites the previous file if one exists, it will
truncate the file to zero length or create a file if it does not exist.
• a+: To append and read data from the file. It won’t override existing data.
• rb: It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.
• rb+: It opens the file to read and write both in binary format. The file pointer
exists at the beginning of the file.
• wb: It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.
• rb+: It opens the file to read and write both in binary format. The file pointer
exists at the beginning of the file.
• wb: It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.
• wb+: It opens the file to write and read both in binary format. The file pointer
exists at the beginning of the file.
• ab: It opens the file in the append mode in binary format. The pointer exists at the
end of the previously written file. It creates a new file in binary format if no file
exists with the same name.
• ab+: It opens a file to append and read both in binary format. The file pointer
remains at the end of the file.
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and
then read it.

f = open("[Link]","r")
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and
then read it.

f = open("[Link]","r")
data=[Link]( )
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and
then read it.

f = open("[Link]","r")
data=[Link]()
Print(data)
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and
then read it.
f = open("[Link]","r")
data=[Link]()
Print(data)
[Link]( )
In the above code, we have passed filename as a first argument and opened file in
read mode as we mentioned r as the second argument. The f holds the file object and
if the file is opened successfully, it will execute the print statement.
[Link]( ) reads the whole file from the current position to the end of the file (also
called EOF),
[Link](b) reads b bytes of the file.
For text files it is usually more convenient to use [Link]() which reads the data
from the current position in the file to the end of that line (also called EOL).
Program code for Write Mode:
It is a write operation in Python. We open an existing file using the given code and
then write on it.
f = open('[Link]','w')
[Link]("Here we write a command")
[Link]("Hello users of CSE")
[Link]()
The close() Method
The close method used to terminate the program. Once all the operations are
done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object. We can perform any operation on
the file externally using the file system which is the currently opened in
Python; hence it is good practice to close the file once all the operations are
done. Earlier use of the close() method can cause the of destroyed some
information that you want to write in your File.
The close() Method
The close method used to terminate the program. Once all the operations are
done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object. We can perform any operation on
the file externally using the file system which is the currently opened in
Python; hence it is good practice to close the file once all the operations are
done. Earlier use of the close() method can cause the of destroyed some
information that you want to write in your File.
Syntax:
[Link]()
The close() Method
The close method used to terminate the program. Once all the operations are done
on the file, we must close it through our Python script using the close() method. Any
unwritten information gets destroyed once the close() method is called on a file
object. We can perform any operation on the file externally using the file system
which is the currently opened in Python; hence it is good practice to close the file
once all the operations are done. Earlier use of the close() method can cause the of
destroyed some information that you want to write in your File.
Syntax:
[Link]()

Example:
f = open("[Link]","r")
data=[Link]()
Print(data)
[Link]( )
Pythonic way of reading a File
Python has a nice way of preventing the loss of data due to unclosed files. The
following code does the same thing as the above one, but without a close statement
(which is done automatically):
Example:
with open(“[Link]", “wt”) as f:
[Link](“Wonderful”) #use with indentation
Pythonic way of reading a File
Python has a nice way of preventing the loss of data due to unclosed files. The
following code does the same thing as the above one, but without a close statement
(which is done automatically):
Example:
with open(“[Link]", “wt”) as f:
[Link](“Wonderful”) #use with indentation

The difference between the traditional approach and the Pythonic one is that the
latter uses a statement with. Once the flow of control exits the block belonging to
with, the file is automatically closed.
os Module
The OS module in Python provides functions for interacting with the operating
system. OS comes under Python’s standard utility modules. This module provides a
portable way of using operating system-dependent functionality.
The *os* and *[Link]* modules include many functions to interact with the file
system.
Python-OS-Module Functions

• Handling the Current Working [Link](), [Link]()


• Creating a [Link](), [Link]()
• Listing out Files and Directories with [Link]()
• Deleting Directory or Files using [Link](), [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()-This function provides the name of the operating system module that it
imports. Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.
import os
print([Link])
Output-
Nt

• [Link]()-It is a mapping object that represents the user’s OS environmental


variables. It returns a dictionary having the user’s environmental variable as key
and their values as value.
import os
print([Link])
Output-
environ({'SHELL': '/bin/bash', 'NV_LIBCUBLAS_VERSION': '[Link]-1',
'NVIDIA_VISIBLE_DEVICES': 'all', 'COLAB_JUPYTER_TRANSPORT': 'ipc‘})
• [Link]()- To change the current working directory this method is used. This
method changes the CWD to a specified path. It only takes a single argument as a
new directory path.
import os
print([Link]())
[Link]('../')
print([Link]())
Output-
C:\Users\sangeeta\AppData\Local\Programs\Python\Python310
C:\Users\sangeeta\AppData\Local\Programs\Python
• [Link]()-To get the location of the current working directory [Link]() is
used.
import os
cwd = [Link]()
print("Current working directory:", cwd)
Output:
Current working directory: C:\Users\sangeeta\AppData\Local\Programs\Python
• [Link]()- method in Python OS env returns the value of the os environment
variable key if it exists otherwise returns the default value.
Syntax: [Link](key, default = None)
• key: string denoting the name of environment variable default (optional) : string
denoting the default value in case key does not exists. If omitted default is set to
‘None’.

import os
key = 'NV_CUDNN_PACKAGE_NAME'
value = [Link](key)
print("Value of 'NV_CUDNN_PACKAGE_NAME' environment variable :", value)
Output-
Value of 'NV_CUDNN_PACKAGE_NAME' environment variable : libcudnn8
• [Link]()-This method in Python is used to create a directory named path with
the specified numeric mode. This method raises FileExistsError if the directory
to be created already exists.
import os
directory = "good"
parent_dir = "/content"
path = [Link](parent_dir, directory)
[Link](path)
print("Directory '%s' created" %directory)
Output-
Directory 'good' created
• [Link]()-This method in Python is used to create a directory
recursively. That means while making leaf directory if any intermediate-level
directory is missing, [Link]() method will create them all.
Example: This code creates two directories, “Nikhil” and “c”, within different parent
directories. It uses the [Link] function to ensure that parent directories are
created if they don’t exist.
import os
directory = "Nikhil"
parent_dir = "D:/Pycharm projects/Authors"
path = [Link](parent_dir, directory)
[Link](path)
print("Directory '% s' created" % directory)
directory = "c"
parent_dir = "D:/Pycharm projects/a/b"
mode = 0o666
path = [Link](parent_dir, directory)
[Link](path, mode)
print("Directory '% s' created" % directory)
• [Link]()-method in Python is used to remove or delete a file path. This method
can not remove or delete a directory. If the specified path is a directory then
OSError will be raised by the method.
import os
[Link]()
'C:\\Users\\sangeeta\\AppData\\Local\\Programs\\Python\\Python310'
file='[Link]'
location='C:\\Users\\sangeeta\\AppData\\Local\\Programs\\Python\\Python310'
path = [Link](location, file)
[Link](path)
• [Link]()-To rename a file or directory in Python you can use [Link]()
function of OS module. This method renames a source file or directory to a
specified destination file or directory. It takes two parameters – source (current file
name) and destination (new file name).

import os
file='C:\\Users\\sangeeta\\AppData\\Local\\Programs\\Python\\Python310\\[Link]'
file1='C:\\Users\\sangeeta\\AppData\\Local\\Programs\\Python\\Python310\\[Link]'
[Link](file,file1)
• [Link]()-method in Python is used to remove or delete an empty directory.
OSError will be raised if the specified path is not an empty directory.
Note-If it contains files or subdirectories, you may encounter an error.

import os
directory = "Goods"
parent = "D:/Pycharm projects/"
path = [Link](parent, directory)
[Link](path)
• [Link]()-The [Link]() method allows us to “start” a file with its associated
program. In other words, we can open a file with it’s associated program, just like
when you double-click a PDF and it opens in Adobe Reader.

Import os
[Link]('C:\Users\mike\Documents\[Link]')

• [Link]()-The [Link]() method gives us a way to iterate over a root level path.
What this means is that we can pass a path to this function and get access to all its
sub-directories and files.
Import os
path = 'C:\Python27\Tools'
for root, dirs, files in [Link](path):
print(root)
Thank You!!!

You might also like