File Handling 1
File Handling 1
File Handling:
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b"- Binary - Binary mode (e.g. images)
Syntax:
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt") The code above is the same as: f = open("demofile.txt",
"rt")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
Note: Make sure the file exists, or else you will get an error.
Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading
the content of the file:
Example:
f = open("demofile.txt", "r")
print(f.read())
Output:
NIT
Example:
f = open("demofile.txt", "r")
print(f.read(5))
Output:
NIT
Read Lines
You can return one line by using the readline() method:
Example:
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
Output:
NIT
By calling readline() two times, you can read the two first lines:
Example:
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Output:
NIT
By looping through the lines of the file, you can read the whole file, line by
line:
Example:
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Output:
NIT
Close Files:
It is a good practice to always close the file when you are done with it
Example:
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Output:
NIT
Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Output:
Now the file has more content!
Example:
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
Output:
Woops! I have deleted the content!
Example:
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Output:
To create myfile
Exercise:
1. Write a Python program to read an entire text file
2. Write a Python program to append text to a file and display
the text.
3. Write a Python program to read last n lines of a file
Assignment:
Write a program to count frequency of characters in a given file. Can you
use character frequency to tell whether the given file is a Python program
file, C program file or a text file? Write a program to count frequency of
characters in a given file. Can you use character frequency to tell whether
the given file is a Python program file, C program file or a text file?
Output:
enter string : Subrata
{'S': 1, 'u': 1, 'b': 1, 'r': 1, 'a': 2, 't': 1}
Write a program to count frequency of characters in a given file. Can you
use character frequency to tell whether the given file is a Python program
file, C program file or a text file?
import collections
import pprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
Output:
File Name: demofile.txt
Counter({'N': 1, 'I': 1, 'T': 1})
Write a program to print each line of a file in reverse order.
Description:
reversed() function produces a reverse iterator
Example:
textfile=open("a_file.txt")
lines=textfile.readlines()
for line in reversed(lines):
print(line)
Output:
Narula Institute of Technology
Write a program to compute the number of characters, words and lines in a
file.
Example:
file=open("sample.txt","r")
number_of_lines=0
number_of_words=0
number_of_characters=0
for line in file:
line=line.strip("\n")#won'tcount \n as character
words=line.split()
number_of_lines+=1
number_of_words+=len(words)
number_of_characters+=len(line)
file.close()
print("lines:", number_of_lines, "words:", number_of_words, "characters:",
number_of_characters)
Output:
lines: 1 words: 6 characters: 45
Write a program to count frequency of characters in a given file.
Example:
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:") Output:
print(k) Enter file name: sample.txt
Enter letter to be searched:n
Occurrences of the letter:
3
END