Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

FileHandling2023 Text File-1

The document discusses the importance of file handling, explaining that files are used to store data permanently on storage devices. It outlines different types of files such as text, binary, and CSV files, along with basic file operations like opening, reading, writing, and closing files. Additionally, it details various file access modes and provides code snippets for performing file manipulations in Python.

Uploaded by

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

FileHandling2023 Text File-1

The document discusses the importance of file handling, explaining that files are used to store data permanently on storage devices. It outlines different types of files such as text, binary, and CSV files, along with basic file operations like opening, reading, writing, and closing files. Additionally, it details various file access modes and provides code snippets for performing file manipulations in Python.

Uploaded by

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

JINI N K

WHY DO WE NEED FILE HANDLING?

 Files are used to store data


permanently
FILE

 A file is a bunch of bytes stored on some


storage device
 Devices like hard disk, thumb drive etc.
 Can be stored permanently and can be
retrieved
TYPES OF FILES

TEXT FILE

BINARY FILE

CSV FILE
TEXT FILES
 Stores information in ASCII or Unicode characters
 Each line of text is terminated with a special
character known as EOL – End Of Line character
(‘\n’, ‘\r \n’)
 Internal translations take place when EOL is read
or written
 Extension for text files is .txt
 Default mode of file
TEXT FILE

REGULAR TEXT DELIMITED TEXT


FILE FILE

TSV FILE CSV FILE


BINARY FILES
 Sores information in the form of a stream of bytes

 Contains information in the same format in which


the information is held in memory

 No delimiter for a line

 No translations required

 Faster and easier than text files

 More secure
CSV FILES

 Comma Separated Values (CSV) file

 Simple file in human readable format

 Used to store tabular data in plain text

 Delimiter is usually a comma

 Easy to generate and import onto a spreadsheet or


database
TEXT FILE VS BINARY
STEPS IN FILE HANDLING
First open the file for read or write by
Opening File specifying the name of file and mode

Read / Write Once the file is opened, can either


read or write

Closing File Close the file after performing the operation


BASIC FILE MANIPULATION

Create Add Delete

Update Search

‫ ﷺ‬Reading data from files

File Operations ‫ ﷺ‬Writing data to files

‫ ﷺ‬Appending data to files


OPENING A TEXT FILE

<file_objectname> = open(<filename>)
OR
<file_objectname> = open(<filename>, <mode>)

File object Name / Path


Mode of a File
created to a File
OPENING A TEXT FILE - EXAMPLE
f = open(“Apple.txt”, ”r”)
• Here “Apple.txt” is loaded in memory and its
reference is linked to ‘f’ object.

• Python will access “Bike.txt” through ‘f’ object

• The file is opened in read mode

File object is also known as File handle


ACCESSING A FILE IN DIFFERENT LOCATION
f = open(“d:\\main\\story.txt”, ”r”)
• Opens file “story.txt” and attaches it to the file object f

• The slashes in the path must be doubled

F = open(r“d:\mydata\poem.txt”,”r”)
• Another solution of double backslash is using “r” before the
path making the string as raw string
i.e. no special meaning attached to any character
OPENING FILES
• The default file-open mode is read mode

• If mode is not specified, Python will open in read mode

• When you open a file in read mode, the given file must
exist in the folder, otherwise Python will raise
FileNotFoundError
FILE ACCESS MODES
File must exist already, otherwise Python
‘r’ Read Only raises I/O errors

• If the file does not exist, file is created.


‘w’ Write Only • If the file exists, Python will truncate existing
data and overwrite the file

• New data will be added to the end of


‘a’ Append existing data, no overwriting
• If file does not exist, Python will create a
new file
• File must exists otherwise error is raised
‘r+’ Read and Write • Both reading and writing can take place

• File is created if not exists


‘w+’ Write and Read • If exists data will be truncated
• Both read and write allowed

• File is created if not exists


‘a+’ Append and • If exists data is retained; new data is
appended
Read • Both read and write allowed
CLOSING A FILE
An opened file is closed by calling the close() method

Syntax: <fileHandle>.close()

Example: f.close()
READING FROM FILES

‫ ﷺ‬read()

‫ ﷺ‬readline()

‫ ﷺ‬readlines()
CREATING A TEXT FILE
1
Open any text editor,
and type any content

2 3
Copy the path from Save your file in the
where your python is path which is copied
installed with .txt extension
read()
Syntax: <fileHandle>.read([n])

• Reads at most n bytes

• If no n is specified, reads the entire file

• Reads the bytes in the form of a string


Reading a file’s entire content f.read()

Code Snippet:

Output 
f.read(n)
Reading a file’s first 30 bytes and printing it.

 Code Snippet

Output 
f.read(n)
Reading n bytes and then reading some
more bytes from the last position read.

 Code Snippet

Output 
readline()
Syntax:
<fileHandle>.readline([n])
• Reads a line of input

• If n is specified, reads at most n bytes

• Returns a blank string if no more bytes are left for


reading in the file

• Reads the bytes in the form of a string


Reading a file’s first line

Code Snippet:
Output:
Reading a file’s first three lines – line by line

Code Snippet:

Output:
Reading a file’s first three lines – line by line

Code Snippet:

Output:
Reading a file using readline(n)

Code Snippet:

Output:
Reading a complete file line by line

Code Snippet: Output:


Reading a file line by line using for loop

Output:
Code Snippet:
Reading a file line by line using for loop

Output:
Code Snippet:
Displaying the size of a file after removing EOL
characters, white spaces & blank lines
Code Snippet: Output:
readlines()
Syntax: <fileHandle>.readlines()

• Reads all lines

• Returns them in a list


Reading a complete file in a list

Code Snippet 

Output:
Program to display the size of a file in bytes

Code Snippet:

Output:
Program to display the number of lines in a file

Code Snippet:

Output:
WRITING ONTO FILES
‫ ﷺ‬write()

‫ ﷺ‬writelines()

• If file doesn’t exists, it will create a new file

• If file exists, it will write the data into the file


write()
Syntax: <fileHandle>.write(str)
• write() method takes a string and writes it in the file

• For storing data, with EOL 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
writelines(seq)
Syntax:
<fileHandle>.writelines(L)

writelines() method is used to write sequence


data types in a file (string, list.)
APPENDING DATA TO A FILE
• Append means to add the data at the end of file
using ‘a’ mode

• If file does not exists, it will create the new file

• If file exists, it will append/add the data at the


end
of the file
Create a text file to hold some data

Code Snippet 

Output 
Create a text file to hold some data

Code Snippet 

Output 
Create a text file to hold student names
Code Snippet :

Input : Text File :


Create a text file to hold student names in different lines

Code Snippet :

Input : Text File :


Create a file with some names separated by newline characters
without using write() function
Code Snippet :

Text File :
Input :
Create a file with some names separated by newline characters
without using write() function

Input : Text File :


Program to get roll numbers, names and marks of the students
of a class and store these details in a file called ‘Marls.txt’

Code Snippet :
Input :

Text File :
Program to add two more students details to the file Marks.txt
created earlier

Code Snippet :
Input : Text File :
Program to display the contents of file ‘Marks.txt’ which is
created earlier

Code Snippet : Output:

OR
Program to read a text file line by line and display each
word separated by a ‘#’

Code Snippet : Output:


Program to read a text file line by line and display the
counts of vowels and consonants in the file.

Code Snippet : Output:


JINI N K

You might also like