TEXT FILE READING & WRITING METHODS
FILE READING PYTHON PROGRA M A Program reads a text/binary file from hard disk. File acts like an input to a program.
FILE READING METHODS Followings are the methods to read a data from the file. 1. readline() METHOD 2. readlines() METHOD 3. read() METHOD
readline() METHOD readline() will return a line read, as a string from the file. First call to function will return first line, second call next line and so on. It's syntax is, fileobject.readline()
readline() EXAMPLE First create a text file and save under filename notes.txt
readline() EXAMPLE
readline() EXAMPLE O/P readline() will return only one line from a file, but notes.txt file containing three lines of text
readlines() METHOD readlines()can be used to read the entire content of the file. You need to be careful while using it w.r.t. size of memory required before using the function. The method will return a list of strings, each separated by n. An example of reading entire data of file in list is: It's syntax is, fileobject.readlines() as it returns a list, which can then be used for manipulation.
readlines() EXAMPLE
readlines() EXAMPLE The readlines() method will return a list of strings, each separated by n
read() METHOD The read() method is used to read entire file The syntax is: fileobject.read() For example Contd…
read() METHOD EXAMPLE
read() METHOD EXAMPLE O/P The read() method will return entire file.
read(size) METHOD
read(size) METHOD read() can be used to read specific size string from file. This function also returns a string read from the file. Syntax of read() function is: fileobject.read([size]) For Example: f.read(1) will read single byte or character from a file.
read(size) METHOD EXAMPLE f.read(1) will read single byte or character from a file and assigns to x.
read(size) METHOD EXAMPLE O/P
WRITING IN TO FILE
WRITING METHODS PYTHON PROGRA M A Program writes into a text/binary file from hard disk.
WRITING METHODS 1. write () METHOD 2. writelines() METHOD
1. write () METHOD For sending data in file, i.e. to create / write in the file, write() and writelines() methods can be used. write() method takes a string ( as parameter ) and writes it in the file. For storing data with end of line character, you will have to add n character to end of the string
write() using “w” mode
write() using “w” mode Lets run the same program again
write() using “w” mode Now we can observe that while writing data to file using “w” mode the previous content of existing file will be overwritten and new content will be saved. If we want to add new data without overwriting the previous content then we should write using “a” mode i.e. append mode.
write() USING “a” MODE New content is added after previous content
2. writelines() METHOD For writing a string at a time, we use write() method, it can't be used for writing a list, tuple etc. into a file. Sequence data type can be written using writelines() method in the file. It's not that, we can't write a string using writelines() method. It's syntax is: fileobject.writelines(seq)
2. writelines() METHOD So, whenever we have to write a sequence of string / data type, we will use writelines(), instead of write(). Example: f = open('test2.txt','w') str = 'hello world.n this is my first file handling program.n I am using python language" f.writelines(str) f.close()
Example Programs Writing String as a record to file
Example :To copy the content of one file to another file
Removing from file whitespaces after reading  read() and readline() reads data from file and return it in the form of string and readlines() returns data in the form of list.  All these read function also read leading and trailing whitespaces, new line characters. If you want to remove these characters you can use functions  strip() : removes the given character from both ends.  lstrip(): removes given character from left end  rstrip(): removes given character from right end
Example: strip(),lstrip(), rstrip()
File Pointer  Every file maintains a file pointer which tells the current position in the file where reading and writing operation will take.  When we perform any read/write operation two things happens:  The operation at the current position of file pointer  File pointer advances by the specified number of bytes.
Example myfile = open(“ipl.txt”,”r”) File pointer will be by default at first position i.e. first character ch = myfile.read(1) ch will store first character i.e. first character is consumed, and file pointer will move to next character
File Modes and Opening position of file pointer FILE MODE OPENING POSITION r, r+, rb, rb+, r+b Beginning of file w, w+, wb, wb+, w+b Beginning of file (overwrites the file if file already exists a, ab, a+, ab+, a+b At the end of file if file exists otherwise creates a new file
Set File offset in Python Tell() Method This method gives you the current offset of the file pointer in a file. Syntax: file.tell() The tell() method doesn’t require any argument. Seek() Method This method can help you change the position of a file pointer in a file. Syntax: file.seek(offset[, from]) The <offset> argument represents the size of the displacement.
file.seek(offset[, from]) The <from> argument indicates the start point. If from is 0, then the shift will start from the root level. If from is 1, then the reference position will become the current position. It from is 2, then the end of the file would serve as the reference position. Example: Setting offsets in Python with open('app.log', 'w', encoding = 'utf-8') as f: #first line f.write('It is my first filen') #second line f.write('This filen') #third line f.write('contains three linesn')
#Open a file f = open('app.log', 'r+') data = f.read(19); print('Read String is : ', data) #Check current position position = f.tell(); print('Current file position : ', position) #Reposition pointer at the beginning once again position = f.seek(0, 0); data = f.read(19); print('Again read String is : ', data) #Close the opened file f.close() Read String is : It is my first file Current file position : 19 Again read String is : It is my first file OUTPUT It is my first file This file contains three lines App.log
Standard INPUT, OUTPUT and ERROR STREAM Most programs make output to "standard out“,input from "standard in“, and error messages go to standard error).standard output is to monitor and standard input is from keyboard. e.g.program import sys a = sys.stdin.readline() sys.stdout.write(a) a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters. #The remaining characters are waiting to be read. sys.stdout.write(a) b = sys.stdin.read(5) sys.stdout.write(b) sys.stderr.write("ncustom error message")
THANK YOU & HAVE A NICE DAY UNDER THE GUIDANCE OF KVS RO AGRA VEDIO LESSON PREPARED BY: KIRTI GUPTA PGT(CS) KV NTPC DADRI

Data file handling in python reading & writing methods

  • 1.
    TEXT FILE READING& WRITING METHODS
  • 2.
    FILE READING PYTHON PROGRA M A Programreads a text/binary file from hard disk. File acts like an input to a program.
  • 3.
    FILE READING METHODS Followingsare the methods to read a data from the file. 1. readline() METHOD 2. readlines() METHOD 3. read() METHOD
  • 4.
    readline() METHOD readline() willreturn a line read, as a string from the file. First call to function will return first line, second call next line and so on. It's syntax is, fileobject.readline()
  • 5.
    readline() EXAMPLE First createa text file and save under filename notes.txt
  • 6.
  • 7.
    readline() EXAMPLE O/P readline()will return only one line from a file, but notes.txt file containing three lines of text
  • 8.
    readlines() METHOD readlines()can beused to read the entire content of the file. You need to be careful while using it w.r.t. size of memory required before using the function. The method will return a list of strings, each separated by n. An example of reading entire data of file in list is: It's syntax is, fileobject.readlines() as it returns a list, which can then be used for manipulation.
  • 9.
  • 10.
    readlines() EXAMPLE The readlines()method will return a list of strings, each separated by n
  • 11.
    read() METHOD The read()method is used to read entire file The syntax is: fileobject.read() For example Contd…
  • 12.
  • 13.
    read() METHOD EXAMPLEO/P The read() method will return entire file.
  • 14.
  • 15.
    read(size) METHOD read() canbe used to read specific size string from file. This function also returns a string read from the file. Syntax of read() function is: fileobject.read([size]) For Example: f.read(1) will read single byte or character from a file.
  • 16.
    read(size) METHOD EXAMPLE f.read(1)will read single byte or character from a file and assigns to x.
  • 17.
  • 18.
  • 19.
    WRITING METHODS PYTHON PROGRA M A Programwrites into a text/binary file from hard disk.
  • 20.
    WRITING METHODS 1. write() METHOD 2. writelines() METHOD
  • 21.
    1. write ()METHOD For sending data in file, i.e. to create / write in the file, write() and writelines() methods can be used. write() method takes a string ( as parameter ) and writes it in the file. For storing data with end of line character, you will have to add n character to end of the string
  • 22.
  • 23.
    write() using “w”mode Lets run the same program again
  • 24.
    write() using “w”mode Now we can observe that while writing data to file using “w” mode the previous content of existing file will be overwritten and new content will be saved. If we want to add new data without overwriting the previous content then we should write using “a” mode i.e. append mode.
  • 25.
    write() USING “a”MODE New content is added after previous content
  • 26.
    2. writelines() METHOD Forwriting a string at a time, we use write() method, it can't be used for writing a list, tuple etc. into a file. Sequence data type can be written using writelines() method in the file. It's not that, we can't write a string using writelines() method. It's syntax is: fileobject.writelines(seq)
  • 27.
    2. writelines() METHOD So,whenever we have to write a sequence of string / data type, we will use writelines(), instead of write(). Example: f = open('test2.txt','w') str = 'hello world.n this is my first file handling program.n I am using python language" f.writelines(str) f.close()
  • 28.
  • 29.
    Example :To copythe content of one file to another file
  • 30.
    Removing from file whitespaces afterreading  read() and readline() reads data from file and return it in the form of string and readlines() returns data in the form of list.  All these read function also read leading and trailing whitespaces, new line characters. If you want to remove these characters you can use functions  strip() : removes the given character from both ends.  lstrip(): removes given character from left end  rstrip(): removes given character from right end
  • 31.
  • 32.
    File Pointer  Everyfile maintains a file pointer which tells the current position in the file where reading and writing operation will take.  When we perform any read/write operation two things happens:  The operation at the current position of file pointer  File pointer advances by the specified number of bytes.
  • 33.
    Example myfile = open(“ipl.txt”,”r”) Filepointer will be by default at first position i.e. first character ch = myfile.read(1) ch will store first character i.e. first character is consumed, and file pointer will move to next character
  • 34.
    File Modes andOpening position of file pointer FILE MODE OPENING POSITION r, r+, rb, rb+, r+b Beginning of file w, w+, wb, wb+, w+b Beginning of file (overwrites the file if file already exists a, ab, a+, ab+, a+b At the end of file if file exists otherwise creates a new file
  • 35.
    Set File offsetin Python Tell() Method This method gives you the current offset of the file pointer in a file. Syntax: file.tell() The tell() method doesn’t require any argument. Seek() Method This method can help you change the position of a file pointer in a file. Syntax: file.seek(offset[, from]) The <offset> argument represents the size of the displacement.
  • 36.
    file.seek(offset[, from]) The <from>argument indicates the start point. If from is 0, then the shift will start from the root level. If from is 1, then the reference position will become the current position. It from is 2, then the end of the file would serve as the reference position. Example: Setting offsets in Python with open('app.log', 'w', encoding = 'utf-8') as f: #first line f.write('It is my first filen') #second line f.write('This filen') #third line f.write('contains three linesn')
  • 37.
    #Open a file f= open('app.log', 'r+') data = f.read(19); print('Read String is : ', data) #Check current position position = f.tell(); print('Current file position : ', position) #Reposition pointer at the beginning once again position = f.seek(0, 0); data = f.read(19); print('Again read String is : ', data) #Close the opened file f.close() Read String is : It is my first file Current file position : 19 Again read String is : It is my first file OUTPUT It is my first file This file contains three lines App.log
  • 38.
    Standard INPUT, OUTPUTand ERROR STREAM Most programs make output to "standard out“,input from "standard in“, and error messages go to standard error).standard output is to monitor and standard input is from keyboard. e.g.program import sys a = sys.stdin.readline() sys.stdout.write(a) a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters. #The remaining characters are waiting to be read. sys.stdout.write(a) b = sys.stdin.read(5) sys.stdout.write(b) sys.stderr.write("ncustom error message")
  • 39.
    THANK YOU & HAVEA NICE DAY UNDER THE GUIDANCE OF KVS RO AGRA VEDIO LESSON PREPARED BY: KIRTI GUPTA PGT(CS) KV NTPC DADRI