0% found this document useful (0 votes)
18 views

3a.file Hadling Online_text

The document provides an overview of file handling in Python, detailing the need for data files, methods of the OS module, and various file operations such as opening, reading, writing, and closing files. It explains different types of data files, file opening modes, and basic operations, along with examples of how to manipulate text files. Additionally, it includes programming exercises related to file handling to reinforce learning.

Uploaded by

Ishaan Gupta
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)
18 views

3a.file Hadling Online_text

The document provides an overview of file handling in Python, detailing the need for data files, methods of the OS module, and various file operations such as opening, reading, writing, and closing files. It explains different types of data files, file opening modes, and basic operations, along with examples of how to manipulate text files. Additionally, it includes programming exercises related to file handling to reinforce learning.

Uploaded by

Ishaan Gupta
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
You are on page 1/ 121

FILE HANDLING

RAM
(RANDOM ACCESS
MEMORY/PRIMARY
MEMORY)
RAM
(RANDOM ACCESS
FILE MEMORY/PRIMARY
MEMORY)

HARD DISK
Need for a data file

• To Store data in organized manner


• To store data permanently
• To access data faster
• To Search data faster
• To easily modify data later on
Methods of os module
(The OS module in python provides functions for interacting with the operating system
system related methods available in os module(standard module) which can be used during file operations)

1. The rename() method used to rename the file.


Syntax os.rename(current_file_name, new_file_name)
2.The remove() method to delete file.
e.g.program
Syntax os.remove(file_name) import os
print(os.getcwd())
3. The mkdir() method of the os module to create directories in the current directory. os.mkdir("newdir")
os.chdir("newdir")
Syntax os.mkdir("newdir")
print(os.getcwd())
4.The chdir() method to change the current directory.
Syntax os.chdir("newdir")
5. The getcwd() method displays the current directory.
Syntax os.getcwd()
NOT IN SYLLABUS THIS YEAR(ADDITIONAL INFORMATION)
6. The rmdir() method deletes the directory.
Syntax os.rmdir('dirname')
Working of os.rename(old_name,new_name)

NOT IN SYLLABUS THIS YEAR(ADDITIONAL INFORMATION)


Returns absolute path (full path) of cwd

Lists files and directories in cwd(. Represents cwd)

NOT IN SYLLABUS THIS YEAR(ADDITIONAL INFORMATION)


>>> os.listdir("E:\2022-23\2022-23\xii cs\ppts\")

SyntaxError: EOL while scanning string literal


>>> os.listdir(r"E:\2022-23\2022-23\xii cs\ppts")
['3a.file hadling online_text.pdf', '3a.file hadling online_text.pptx',
'connecting_sql_python_online.pdf',
'connecting_sql_python_online.pptx', 'formatted string online.pdf',
'library module packages online.pdf', 'library module packages
online.pptx', 'Plotting Graphs_ONLINE.pdf', 'Tkinter online.pdf', 'Tkinter
online.pptx', '~$3a.file hadling online_text.pptx']
>>> os.listdir(r"E:\2022-23\2022-23\xii cs\")

SyntaxError: EOL while scanning string literal


>>> os.listdir(r"E:\2022-23\2022-23\xii cs")
['class test', 'exam paper', 'ppts', 'practical file']
>>> os.chdir(r"E:\2022-23\2022-23\xii cs")
>>> os.getcwd()
'E:\\2022-23\\2022-23\\xii cs'
>>> os.chdir('.')
>>> os.getcwd()
'E:\\2022-23\\2022-23\\xii cs'
>>> os.chdir('..')
>>> os.getcwd()
'E:\\2022-23\\2022-23'
>>> os.chdir(r'\xii cs\ppts')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
os.chdir(r'\xii cs\ppts')
FileNotFoundError: [WinError 3] The system
cannot find the path specified: '\\xii cs\\ppts'
>>> os.chdir(r'.\xii cs\ppts')
>>> os.getcwd()
'E:\\2022-23\\2022-23\\xii cs\\ppts'
Absolute Path vs Relative Path
The absolute path is the full path to some place on your computer.

The relative path is the path to some file with respect to your current working
directory (CWD).

For example:

Absolute path: C:/users/admin/docs/staff.txt


If CWD is C:/users/admin/, then the relative path to staff.txt would be:
docs/staff.txt

Note, PWD + relative path = absolute path.


File Handling
• A file is a sequence of bytes on the disk.
• Needed for permanent storage where a group of related data is
stored.
• For retreiving data later to generate reports.
• File handling in Python enables us to create, update, read, and
delete the files stored on the file system.
• In Python, File Handling consists of following three steps:
Open the file.
Process file i.e perform read or write operation.
Close the file.
Types of Data File
Text Files- A file whose contents can be viewed using a text editor is called a text file. A text file is simply a
sequence of ASCII or Unicode characters. Python programs, contents written in text editors are some of the
example of text files.e.g. .txt,.rtf,.csv etc.

Binary Files-A binary file stores the data in the same way as as stored in the memory. The .exe files,mp3 file,
image files are some of the examples of binary files. We can’t read a binary file using a text editor.e.g.
.bmp,.cdr etc.

Text File Binary File


Less prone to get corrupt as change reflects as Can easily get corrupted, corrupt on even single
soon as made and can be undone. bit change
Store only plain text in a file. Can store different types of data (audio,
text,image) in a single file.
Widely used file format and can be opened in any Developed for an application and can be opened
text editor. in that application only.
Mostly .txt,.rtf are used as extensions to text files. Can have any application defined extension.
Opening file using open() Function

• open() creates file object for file operations.


• Syntax
• File_object = open(<file_name>, <access_mode>)

file_name = name of the file ,enclosed in double quotes.

access_mode= Determines what kind of operations can


be performed with file,like read,write etc.
Opening file using WITH statement

• open() creates file object for file operations.


• Syntax
File_object = open(<file_name>, <access_mode>)

with open (file_name, access_mode) as file_ object:


file_name = name of the file ,enclosed in double quotes.

access_mode= Determines what kind of operations can


be performed with file,like read,write etc.

Note: NO need to close the file explicitly as the resources get free as soon as the execution of with block gets over
File opening modes (for reading)

SNo Mode & Description


1 r - reading only.Sets file pointer at beginning of the
file . This is the default mode. It doesn’t create new
file, if file doesn’t exists[returns error].
2 rb – same as r mode but with binary file
3 r+ - both reading and writing. The file pointer placed
at the beginning of the file.
4 rb+ - same as r+ mode but with binary file
File opening modes (for writing)

SNo Mode & Description


5 w - writing only. Overwrites the file if the file
exists. If not, creates a new file for writing.
6 wb – same as w mode but with binary file.
7 w+ - both writing and reading. Overwrites . If no
file exist, creates a new file for R & W.
File opening modes (for appending)
SNo Mode & Description
9 a -for appending. Move file pointer at end of the file.
Creates new file for writing, if file doesn’t exist.
10 ab – same as a but with binary file.
11 a+ - for both appending and reading. Move file pointer at
end. If the file does not exist, it creates a new file for
reading and writing.
12 ab+ - same as a+ mode but with binary mode.
Basic Text file operations

• Open (filename – absolute or relative path, mode)


• Reading/Writing data
• Manipulation of data
• Appending data into a text file
• Close a text file
Open() function to open a file and concept of raw string
• open() creates file object which serves as a link to the file for file operations.
Syntax
• File_object = open(<file_name>, <access_mode>)

r in front of a string makes it


raw string that means there is
no special meaning attached
to any character
Though I opened my
file but my cwd is still
c://python37
File object attributes

 closed: It returns true if the file is closed and false when


the file is open.
 mode: Returns file opening mode
 name: Returns the name of the file which file object
holds.
Note the way of opening the file. Instead
of two \\ backward slash or raw string, I
have simply used single forward slash

If you just give the filename without its path (e.g., just
“a.txt” rather than “c:/python37/file handling/a.txt”),
python will open or create the file in the same directory
in which the module file is stored
Always Close a text file to free the resources i.e. memory
close(): Used to close an open file. After using this method,an opened file will be
closed and a closed file cannot be read or written any more.
Sample code:
#file opened in append mode
f = open("a.txt", 'a+')
#checking if file is open
print(f.closed) #checking if the file is closed
print("Name of the file is",f.name)
f.close() #to close text file
print(f.closed) #checking if the file is closed
OUTPUT Note:
False closed is an attribute of
Name of the file is a.txt file object whereas
True close() is a
method/function
Writing onto a text file :

The write() Method


It writes the contents to the file in the form of string. It does not return value.
Due to buffering, the string may not actually show up in the file until the flush()
or close() method is called.
Syntax:
<filehandle>.write(str1) #writes string str1 to file referenced by <filehandle>
Sample code:

f=open("c:/python37/file handling/a.txt",'w')
f.write("hello\nhow are \tyou")
f.close()
Writing onto a text file :

The writelines() Method


It writes all strings in list L as lines.
Syntax:
<filehandle>.writelines(list)
Writing onto a text file :

The writelines() Method


It writes all strings in list L as lines.
Syntax:
<filehandle>.writelines(list)

You may pass a tuple and


dictionary as well but it
should contain strings only. If
any other type of data is given
then python returns error.
Write a program using write() function to create a file
student.dat to hold names of your 5 friends. Output should be
as follows:

Open the file


Use loop
3Read the name
4Send name to the file
Repeat steps 3 and 4 5 times
Close the file
Write a program using write() function to create a file
student.dat to hold names of your 5 friends. Output should be
as follows: .py file

write() function doesnot add any extra character


like newline character(‘\n’) after every write
operation
Write a program using write() function to create a file
student.dat to hold names of your 5 friends. Sample run and
Output should be as follows:

OUTPUT SAMPLE RUN


Write a program using write() function to create a file
student.dat to hold names of your 5 friends. Sample run and
Output should be as follows: .py file
Write a program to create a file with few names separated by newline characters without using write() function
Write a program to create a file with few names separated by newline characters without using write() function
Adding
records
of any
object
type into
the text
file, here
student
Difference between flush() and close()

Python automatically flushes the files when closing


them by calling flush() function. It means this function
is implicitly called by close() function.

Why should I use


flush() function when
close() implicitly calls
it????
Why should I use
flush() function when
Difference between flush() and close() close() implicitly calls
it????

Sending data partially without closing the file


Reading from a file
Method Syntax Description
read() <file_handle>.read([n]) • Returns the read bytes in form of a string.
• Reads n bytes.
• If no n is specified, reads the entire file.
readline() <file_handle>.readline([n]) • Reads a line of the file and returns in form of
a string.
• For specified n, reads at most n bytes.
• However, does not read more than one line,
even if n exceeds the length of the line.
• Returns a blank string if no more bytes are
left for reading in the file
readlines() <file_handle>.readlines() • Reads all lines and returns them in a list.
• Reads only one line if n is given as argument
File as ….to be discussed with [not in book]
iterator programs
read() function [without argument n]
read(n) function [with argument n]
readline() function [without argument n]
readline(n) function [with argument n]
Reads n bytes
readline(n) function [with argument n]
Does not read more than one line, even if n exceeds the
length of the line.
readlines() function [without argument n]
Reads all lines and return them in a list
readlines(n) function [with argument n]
Reads only 1 line as a list no matter what’s the value of n
Use of strip() function

strip() function
removes the leading
and trailing white
spaces(new line
character/space

lstrip() : removes white


spaces from the left

rstrip() : removes white


spaces from the right
Text file questions
SNO QUESTION
1. Program to read content of text file “notes.txt” and display content of a file using read() method.
2. Program to read content of text file “notes.txt” and display content of a file using open() method.
[example of file as an iterator]
3. Program to count number of vowels in notes.txt
4. Program to display # after every word from the file notes.txt
5. Program in python to type text in a file till ~ is pressed as rightmost character
6. Program in python to read first 2 lines from text file
7. Program in python to append text at the end of text file
8. Program in python to read line by line from text file
9. Program in python to read entire file line by line in a list
10. Program in python to display each word ina separate line
11. Program in python to count no. of words in a text file
12. Program in python to show word with maximum length from a text file
13. Program in python to display frequency of each word in a text file
14. Program in python to store list elements (having days of the week) in a file and read these contents from
file again
Text file questions
SNO QUESTION
15. Python program to combine each line from first file with the corresponding line in second file
16. Python Program to Copy the Contents of One File into Another (notes to notes3)
17. Python Program to Search for a word in text file and print part of line[searching for flying in notes.txt]
18. Python Program to read character by character from a text file
19. Python Program to convert file contents upper to lower and lower to upper case in the same opened file.
20. WAP to find the lines in a text file that start with a digit/number.
21. WAP to print the last line of a text file
22. WAP to print the longest line of a text file
23. WAP to copy the lines that start with Capital letters of a text file and paste it to a new file.
24. WAP that will read a text file notes.txt and displays all lines not starting with ‘h’
25. WAP that will read a text file notes.txt and will copy all those words whose length is four or more to
another file info.txt
26. WAP that will take a user defined file name. The program should copy all the data from this file to
another file copy.txt.
27. WAP to copy all the words starting with ‘F’ from the file to another text file info.txt.
28. WAP to copy all file lines that start with a lowercase letter from the notes.txt file into info.txt
Program to read content of text file “notes.txt” and display content of a file using read() method.
file=open("notes.txt","r")
data=file.read()
print("printing entire contents")
print(data)
file.close() # to close “notes.txt”.

Back
Program to read content of text file “notes.txt” and display content of a file using open()
method. [example of file as an iterator]

Back
Program to read content of text file “try.txt” and display content of a file character by character
using open() method. [example of file as an iterator]

#using file as an iterator instead of using read()/readline()/readlines() functions


def file_as_iterator_ch(): ==== RESTART: C:/python37/CLASS 12/file handling/text file/21-22/demo.py ====
<_io.TextIOWrapper name='try.txt' mode='r' encoding='cp1252'>
f=open("try.txt") hello
print(f) #printing f(file object) won't print data...it prints
h
#name of the opened file and the file mode e
for line in f: #moving line by line l
l
print(line) o
for ch in line: #moving character by character
print(ch) how are

h
file_as_iterator_ch() o
w

a
r
e

you
y
o Back
u
Program to read content of text file “try.txt” and display content of a file word by word using
open() method. [example of file as an iterator]

==== RESTART: C:/python37/CLASS 12/file handling/text file/21-22/demo.py ====


def file_as_iterator_word(): <_io.TextIOWrapper name='try.txt' mode='r' encoding='cp1252’>
hello
f=open("try.txt")
print(f) hello
how are
for line in f: #moving line by line
print(line) how
are
line=line.split() #used split() to split line into list of words you
for word in line: #tranversing through list of words you
print(word)

file_as_iterator_word()

Back
3. Program to count number of vowels in notes.txt

Back
4. Program to display # after every word from the file notes.txt

Back
5. Program in python to type text in a file till ~ is pressed as rightmost character

To extract last character read to check if it’s ~

Back
6. Program in python to read first 2 lines from text file

Back
7. Program in python to append text at the end of text file

Back
8. Program in python to read line by line from text file

Back
9. Program in python to read entire file in a list

Back
10. Program in python to display each word in new separate line

Back
11. Program in python to count no. of words in a text file

Back
12. Program in python to show word with maximum length from a text file

Back
13. Program in python to display frequency of each word in a text file

Back
14. Program in python to store list elements (having days of the week) in a file and read
these contents from file again

Back
15. Python program to combine each line from first file with the corresponding line in second file

Back
16. Python Program to Copy the Contents of One File into Another (notes to
notes3)

Back
17. Python Program to Search for a word in text file and print part of line[searching for flying
in notes.txt]

Back
18. Python Program to read character by character from a text file

Back
19. Python Program to convert file contents upper to lower and lower to upper case in the
same opened file.

Back
20. WAP to find the lines in a text file that start with a digit/number.

Back
21. WAP to print the last line of a text file

Back
22. WAP to print the longest line of a text file

Back
23. WAP to copy the lines that start with Capital letters of a text file and paste it to a new file.

Back
24. WAP that will read a text file notes.txt and displays all lines not starting with ‘h’

Back
25. WAP that will read a text file notes.txt and will copy all those words whose length is four or more to
another file info.txt

Back
26. WAP that will take a user defined file name. The program should copy all the data from this file to
another file copy.txt.

Back
27. WAP to copy all the words starting with ‘F’ from the file to another text file info.txt.

Back
28. WAP to copy all file lines that start with a lowercase letter from the notes.txt file into info.txt

Back
Text file questions
SNO QUESTION
29. A text file contains alphanumeric text(say notes.txt). Write a program that read this text file and sends
only the numbers from this file to other file.
30. WAP in PYTHON to display the last 3 characters of a text file “NOTES4.TXT’.
31. Consider the following code:
ch = "A"
f=open("data.txt",'a')
f.write(ch)
print(f.tell())
f.close()
What is the output if the file content before the execution of the program is the string "ABC"? (Note that“
" are not the part of the string)
32. Consider the following code:
ch = "A"
f=open("data.txt",’w')
f.write(ch)
print(f.tell())
f.close()
What is the output if the file content before the execution of the program is the string "ABC"? (Note that"
" are not the part of the string)
29. A text file contains alphanumeric text(say notes.txt). Write a program that read this text file and sends
only the numbers from this file to other file

Back
30. WAP in PYTHON to display the last 3 characters of a text file “NOTES4.TXT’.

Back
31. Consider the following code:
ch = "A"
f=open("data.txt",'a')
f.write(ch)
print(f.tell())
f.close()
What is the output if the file content before the execution of the program is the string "ABC"? (Note that" " are
not the part of the string)

Back
32. Consider the following code:
ch = "A"
f=open("data.txt",’w')
f.write(ch)
print(f.tell())
f.close()
What is the output if the file content before the execution of the program is the string "ABC"? (Note that" " are
not the part of the string)

Back
Text file questions
SNO QUESTION
33. Assuming that a text file named TEXT1.TXT already contains some text written into it, write a function named
vowelwords(), that reads the file TEXT1.TXT and creates a new file named TEXT2.TXT, which shall contain only
those words from the file TEXT1.TXT which don’t start with an uppercase vowel (i.e., with ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). For
example, if the file TEXT1.TXT contains Carry Umbrella and Overcoat When It rains
Then the text file TEXT2.TXT shall contain Carry and When rains
34. Assuming that a text file named TEXT1.TXT already contains some text written into it, write a function named
vowelwords(), that reads the file TEXT1.TXT and creates a new file named TEXT2.TXT, which shall contain only
those words from the file TEXT1.TXT which start with an uppercase vowel (i.e., with ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). For
example, if the file TEXT1.TXT contains Carry Umbrella and Overcoat When It rains
Then the text file TEXT2.TXT shall contain Umbrella Overcoat It
35. Write a function in PYTHON to count the number of lines ending with a vowel from a text file “notes.TXT’.
36. Write a function to count and display the number of blanks present in a text file named “NOTES2.TXT”.
37. Write a function in PYTHON to count and display the number of words starting with alphabet ‘A’ or ‘a’ present in
a text file “lines.TXT”. Example:
If the file “LINES.TXT” contains the following lines,
A boy is playing there. There is a playground.
An aeroplane is in the sky.
Are you getting it?
The function should display the output as 5.
33. Assuming that a text file named TEXT1.TXT already contains some text written into it, write a function named
vowelwords(), that reads the file TEXT1.TXT and creates a new file named TEXT2.TXT, which shall contain only those
words from the file TEXT1.TXT which don’t start with an uppercase vowel (i.e., with ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). For example,
if the file TEXT1.TXT contains Carry Umbrella and Overcoat When It rains
Then the text file TEXT2.TXT shall contain Carry and When rains

Back
34. Assuming that a text file named TEXT1.TXT already contains some text written into it, write a function named
vowelwords(), that reads the file TEXT1.TXT and creates a new file named TEXT2.TXT, which shall contain only those
words from the file TEXT1.TXT which start with an uppercase vowel (i.e., with ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). For example, if the
file TEXT1.TXT contains Carry Umbrella and Overcoat When It rains
Then the text file TEXT2.TXT shall contain Umbrella Overcoat It

Back
35. Write a function in PYTHON to count the number of lines ending with a vowel from a text file “notes.TXT’.

Back
36. Write a function to count and display the number of blanks present in a text file named “NOTES2.TXT”.

Back
37. Write a function in PYTHON to count and display the number of words starting with alphabet ‘A’ or ‘a’ present in a text file
“lines.TXT”. Example: If the file “LINES.TXT” contains the following lines,
A boy is playing there. There is a playground.
An aeroplane is in the sky.
Are you getting it?
The function should display the output as 5.

Back
Text file questions
SNO QUESTION
38. Write a function show(n) that will display the nth character from the existing file “LINES.TXT”. If the total
characters present are less than n, then it should display “invalid n”.
39. Write a function in PYTHON that counts the number of “is” or “in” words present in a text file “LINES.TXT”.
40. Write a function EUCount() in PYTHON, which should read each character of a text file IMP.TXT, should count and
display the occurrences of alphabets E and U (including small cases e and u too).
41. Write a function in Python which accepts two text file names as parameters. The function should copy the
contents of first file into the second file in such a way that all multiple consecutive spaces are replaced by a
single space.
42. Write a function in Python to input a multi-line string from the user and write this string into a file named
‘Story.txt’. Assume that the file has to be created.
43. Write a program to display the last line of a text file.
44. Write a Python function to read and display a text file ‘notes.TXT'. At the end display number of lowercase
characters, uppercase characters, and digits present in the text file.
45. Write a Python function to display the size of a text file after removing all the white spaces (blanks, tabs, and
EOL characters).
46. Write a python program to read last 2 lines of a text file.
47. Write a python program to print from line 2 to line 5 (assuming the file has more than 5 lines)
38. Write a function show(n) that will display the nth character from the existing file “LINES.TXT”. If the total characters present
are less than n, then it should display “invalid n”.

Back
39. Write a function in PYTHON that counts the number of “is” or “in” words present in a text file “LINES.TXT”.

Back
40. Write a function EUCount() in PYTHON, which should read each character of a text file IMP.TXT, should count and display the
occurrences of alphabets E and U (including small cases e and u too).

Back
41. Write a function in Python which accepts two text file names as parameters. The function should copy the contents of first
file into the second file in such a way that all multiple consecutive spaces are replaced by a single space.

Back
42. Write a function in Python to input a multi-line string from the user and write this string into a file named ‘Story.txt’. Assume
that the file has to be created.

Back
43. Write a program to display the last line of a text file.

Back
44. Write a Python function to read and display a text file ‘notes.TXT'. At the end display number of lowercase characters,
uppercase characters, and digits present in the text file.

Back
45. Write a Python function to display the size of a text file after removing all the white spaces (blanks, tabs, and EOL
characters).

Back
46. Write a python program to read last 2 lines of a text file.

Back
47. Write a python program to print from line 3 to line 6 (assuming the file has more than 5 lines)

Back
Text file questions
SNO QUESTION
48. Write a python program to insert a new line at the beginning of the file
49. Write a python program to move the contents of a file to an list
50. What Will Be the Output of the Following Code Snippet?
fo = open("myfile.txt", "w+")
print ("File name is : ", fo.name)
seq="File handling is easy in python"
fo.writelines(seq)
fo.seek(0,0)
for line in fo:
print (line)
fo.close()
51. What Will Be The Output Of The Following Code Snippet?
fo = open("a.txt", "w+")
print ("File name is : ", fo.name)
txt = "This is 1st line,"
fo.writelines( txt )
seq = " This is 2nd line, This is 3rd line"
fo.seek(0, 2)
fo.writelines( seq )
fo.seek(0,0)
48. Write a python program to insert a new line at the beginning of the file

Back
49. Write a python program to move the contents of a file to an list

Back
50. Predict the output

Back
51. Predict the output

Back
Text file questions
SNO QUESTION
52. The following sample file called studentmarks.txt contains one line for each student in an imaginary class. The
students name is the first thing on each line, followed by some exam scores. The number of scores might be
different for each student.
Mohak 10 15 20 30 40
Manish 23 16 19 22
Ria 8 22 17 14 32 17 24 21 2 9 11 17
Joy 12 28 21 45 26 10
Freya 14 32 25 16 89
Using the text file studentmarks.txt write a program that prints out the names of students that have more than
five quiz scores.
53. Write a Python Program that Reads a Text File and Counts the Number of Times each character appears in the
Text File
54. Write a Python Program that Reads a Text File and Counts the Number of Times a Certain Letter Appears in the
Text File
55. Write a Python Program to Read a File and Capitalize the First Letter of Every Word in the File.
56. Write a Python Program to Read the Contents of a File in Reverse order i.e. your program should read last
line..then second last line and so on till the first line
52. The following sample file called studentmarks.txt contains one line for each student in an imaginary class. The students
name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
Mohak 10 15 20 30 40
Manish 23 16 19 22
Ria 8 22 17 14 32 17 24 21 2 9 11 17
Joy 12 28 21 45 26 10
Freya 14 32 25 16 89
Using the text file studentmarks.txt write a program that prints out the names of students that have more than five quiz scores.

Back
53. Write a Python Program that Reads a Text File and Counts the Number of Times each character appears in the Text File

Back
54. Write a Python Program that Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File

Back
55. Write a Python Program to Read a File and Capitalize the First Letter of Every Word in the File.

Back
56. Write a Python Program to Read the Contents of a File in Reverse order i.e. your program should read last line..then second
last line and so on till the first line

Back
RANDOM ACCESS METHODS
RANDOM ACCESS METHODS

All reading and writing functions


discussed till now, work sequentially in the file.
To access the contents of file randomly –
following methods are use.

seek method

tell method
seek method

seek()method can be used to position the


file object at particular place in the file.
It's syntax is :

fileobject.seek(offset [, from_what])
here offset is used to calculate the
position of fileobject in the file in bytes. Offset
is added to from_what (reference point) to get
the position. Following is the list of from_what
values:
seek method

Value reference point

0 beginning of the file


1 current position of file
2 end of file

default value of from_what is 0, i.e. beginning


of the file.
seek method

f.seek(7) keeps file pointer at reads the file


content from 8th position onwards to till EOF.
seek method

Results: - So 8th position onwards to till EOF.


Reading according to size

In the input function if you specify the


number of bytes that many number of bytes
can be fetched and assigned to an identifier.
Reading according to size

f.read(1) will read single byte/ character


starting from byte number 8. hence byte
number 8 is P so one character/byte is fetched
and assigned to f_data identifier.
Reading according to size

f.read(2) - will read 2 chars/bytes


f.read(4) - will read 4 chars/bytes

and so on..
tell method

tell() method returns an integer giving


the current position of object in the file. The
integer returned specifies the number of bytes
from the beginning of the file till the current
position of file object.

It's syntax is

fileobject.tell()
tell() method
tell() method

tell() method returns an integer and


assigned to pos variable. It is the current
position from the beginning of file.
TEXT FILES OVER

You might also like