[go: up one dir, main page]

0% found this document useful (0 votes)
115 views17 pages

File Handling 1

The document discusses file handling in Python. It covers opening, reading, and writing to files. The key points are: 1) The open() function is used to open a file, specifying the filename and mode (read, write, append, etc.). 2) Files can be read using methods like read(), readline(), or by looping through lines. Only part of the file can be read as well. 3) It is important to close files after opening to avoid issues. 4) Files can be written to or appended to depending on the mode used with open(). New files can also be created. 5) Examples are provided to demonstrate reading, writing, creating and manipulating file contents

Uploaded by

Shilpita Jana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views17 pages

File Handling 1

The document discusses file handling in Python. It covers opening, reading, and writing to files. The key points are: 1) The open() function is used to open a file, specifying the filename and mode (read, write, append, etc.). 2) Files can be read using methods like read(), readline(), or by looping through lines. Only part of the file can be read as well. 3) It is important to close files after opening to avoid issues. 4) Files can be written to or appended to depending on the mode used with open(). New files can also be created. 5) Examples are provided to demonstrate reading, writing, creating and manipulating file contents

Uploaded by

Shilpita Jana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

File Handling

File Handling:
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

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.

Open a File on the Server


Assume we have the following file, located in the same folder as Python:
demofile.txt

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

Read Only Parts of the File


By default the read() method returns the whole text, but you can also specify
how many characters you want to return:

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

To write to an existing file, you must add a parameter to the open()


function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example:
Open the file "demofile2.txt" and append content to 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!

Note: the "w" method will overwrite the entire file


Create a New File:
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

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?

str=input("enter string : ")


f = {}
for i in str:
if i in f:
f[i] += 1
else:
f[i] = 1
print(f)

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

You might also like