Why do we need to study this?
Most of the scripts (i.e. python programs) we use takes input from the user and printed the result on the shell but nothing could be saved or retrieved
With Files we can store result on the HDD (i.e. secondary storage) to be used later
What is a File?
A File is a collection of records i.e. a collection of data on a secondary storage with associated information (i.e. Metadata) like the Filename and the type of file, permission etc.
A File is used to store data like an image file consisting of pixel data
Types of Files that we will work with
Data Files – are the files that store data from an application or to be used by an application later
Syntax:
<file_objectname>=open(<filename>,<mode>)
Example:
File open modes:
Two ways to give path in filenames correctly are:
1. Double the slashes e.g.
Handling Errors that may occur:
There may be condition where the file we are trying to open in not there or we does not have permission to access it, then an Exception may occur which if not handled properly may crash the entire program. So we have to open a file inside a try finally block
Function that can be used to write onto files are:
2. writelines():
Syntax:
<filehandle>.writeline(L) #writes all the string in list L as lines to file
Example:
Appending to Files:
When we open a file in 'w' (i.e. in write mode ), we overwrite the existing data in the file which may be undesirable so we use the append mode. so it allows to write in the file without overwriting the existing data:
Syntax:
<filehandle>=open(<filename>, 'a')
<filehandle>.write(str)
Example:
Reading From a File:
ways to read from are listed below:
Syntax:
<filehandle>.read(n)
Example:
Reads a line of input. If n is specified reads at most n bytes. returns the read bytes in the form of a string ending within ln(line) character or return a blank string if no more bytes are left for reading in the fileMost of the scripts (i.e. python programs) we use takes input from the user and printed the result on the shell but nothing could be saved or retrieved
With Files we can store result on the HDD (i.e. secondary storage) to be used later
What is a File?
A File is a collection of records i.e. a collection of data on a secondary storage with associated information (i.e. Metadata) like the Filename and the type of file, permission etc.
A File is used to store data like an image file consisting of pixel data
Types of Files that we will work with
Data Files – are the files that store data from an application or to be used by an application later
- Text Files: Stores data in ASCII or Unicode character and each text line is terminated by EOL(End Of Line). In Python the Default EOL is ‘\n’
- Binary File: A binary file is dump of the data in the same format as was held in memory by an application i.e. the file content that is returned is RAW. There is no delimiter for a line of a data.
OPERATION ON FILES:
Opening files:Syntax:
<file_objectname>=open(<filename>,<mode>)
Example:
- fl=open('newFile1.txt', 'w') #when opening new file 'w' i.e. write mode should be used
- #when the file to be opened is in the same directory as the script
- fl1=open('c:\\main\\newFile.txt','w') # to be opened from a particular directory
Text File Mode | Binary File Mode | Description | Notes |
'r' | 'rb' | read only | File must exist already, otherwise Python raise I/O error |
'w' | 'wb' | write only | 1. if the file does not exists, file is created 2. if the file exists, Python will truncate existing data and over-write in the file. So this mode must be used with caution |
'a' | 'ab' | append | 1. File is in write only mode. 2. if the file exits, the data in the file is retained and new data being written will be appended to the end 3. if the file does not exist, Python will create a new file |
'r+' | 'r+b' or 'rb+' | read and write | 1. File must exist otherwise error is raised 2. Both reading and writing operations can takes place |
'w+' | 'w+b' or 'wb+' | write and read | 1. File is created if does not exits. 2. If file exits, file is truncated (past data is lost) 3. Both reading and writing operatins can take place |
'a+' | 'a+b' or 'ab+' | write and write | 1. File is created if does not exits 2. If file exists, file's existing data is retained; new data is appended. 3. Both reading and writing operations can take place |
1. Double the slashes e.g.
- f=open('c:\\temp\\data.txt','r')
2. Give raw string by prefixing the file-path string with an r e.g.
- f=open(r'c:\temp\data.txt','r')
File object/File Handle:
A file object (also known as File handle) is a reference to a file on disk. It opens and makes it available for a number of different task.
Closing a File:
Syntax:
<fileHandle>.close()
Example:
- f=open('file.txt','w')
- f.close()
Handling Errors that may occur:
There may be condition where the file we are trying to open in not there or we does not have permission to access it, then an Exception may occur which if not handled properly may crash the entire program. So we have to open a file inside a try finally block
- try:
- f = open("test.txt","w")
- # perform file operations
- finally:
- f.close()
Function that can be used to write onto files are:
- write():
<filehandle>.write(str) #writes string str to file referenced by <filehandle>
Example:
- f = open("test.txt","w")
- f.write("this is a line that will be written ")
2. writelines():
Syntax:
<filehandle>.writeline(L) #writes all the string in list L as lines to file
Example:
- f = open("test.txt","w")
- ls=["Jack and Jill went up the hill \n","To fetch a pail of water \n"]
- f.writelines(ls)
- f.close()
Appending to Files:
When we open a file in 'w' (i.e. in write mode ), we overwrite the existing data in the file which may be undesirable so we use the append mode. so it allows to write in the file without overwriting the existing data:
Syntax:
<filehandle>=open(<filename>, 'a')
<filehandle>.write(str)
Example:
- fl = open("myfile.txt","a") #append mode
- fl.write("its a new data \n")
- fl.close()
Reading From a File:
ways to read from are listed below:
- read():
Syntax:
<filehandle>.read(n)
Example:
- fl = open("myfile.txt","r+") #append mode
- print(fl.read(20))
- fl.close()
- readline(n):
Syntax:
<filehandle>.readline(n)
Example:
- fl=open('newFile.txt','r+')
- sti=fl.readline()
- print(sti)
- fl.close()
Output:
Syntax:
<filehandle>.readlines()
Example:
- ==== RESTART: D:/pythonVirtualEnv/practicePro/examplePro/fileHandling.py ====
- we work we try to be better
- readlines():
Syntax:
<filehandle>.readlines()
Example:
- fl=open('newFile.txt','r+')
- ls=fl.readlines()
- print(type(ls))
- print(ls)
- ==== RESTART: D:/pythonVirtualEnv/practicePro/examplePro/fileHandling.py ====
- <class 'list'>
- ['we work we try to be better\n', 'we work we try to be better\n', 'we work we try to be better']