[go: up one dir, main page]

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

Files

Uploaded by

Sagana C. CSE
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)
20 views17 pages

Files

Uploaded by

Sagana C. CSE
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

FILES

Types Of File in Python


• Idea of “persistent” programs that keep data in permanent storage like file,
database
• Binary file
• Text file
• Binary files in Python
Example:
1.Document files: .pdf, .doc, .xls etc.
2.Image files: .png, .jpg, .gif, .bmp etc.
3.Video files: .mp4, .3gp, .mkv, .avi etc.
4.Audio files: .mp3, .wav, .mka, .aac etc.
5.Database files: .mdb, .accde, .frm, .sqlite etc.
6.Archive files: .zip, .rar, .iso, .7z etc.
7.Executable files: .exe, .dll, .class etc.
Text files in Python

• Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Python File Handling Operations

• 4 types of operations that can be handled by Python on files


• Open
• Read
• Write
• Close
Create and Open a File

• Syntax:
file_object = open(file_name, mode)
• ‘r’ – Read Mode: read data from the file.
• ‘w’ – Write Mode: write data into the file or modify it.
• ‘a’ – Append Mode: Append mode is used to append data to the file.
• ‘r+’ – Read or Write Mode: write or read the data from the same file.
• ‘a+’ – Append or Read Mode: read data from the file or append the
data into the same file.
Read From File
• Text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM
• three ways in which we can read the files in python
• read([n])
• readline([n])
• readlines()
• Example1
• my_file = open(“C:/Documents/Python/test.txt”, “r”)
• print(my_file.read(5))
• Example2
• my_file = open(“C:/Documents/Python/test.txt”, “r”)
• print(my_file.read())
• Example3
• my_file = open(“C:/Documents/Python/test.txt”, “r”)
• print(my_file.readline()) # read the content of the file on a line by line
• Example4
• my_file = open(“C:/Documents/Python/test.txt”, “r”)
• print(my_file.readlines()) # reading all the lines present inside the text file including the newline characters
Write to File
• To write data into a file, we must open the file in write mode.
• write(string)
• writelines(list)
• Example 1:
• my_file = open(“C:/Documents/Python/test.txt”, “w”)
• my_file.write(“Hello World”)
• Example 2:
• fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
• my_file = open(“C:/Documents/Python/test.txt”, “w”)
• my_file.writelines(fruits)
Append to File

• Example 1:
• my_file = open(“C:/Documents/Python/test.txt”, “a+”)
• my_file.write (“Strawberry”)
Python Close File

• Example 1:
• my_file = open(“C:/Documents/Python/test.txt”, “r”)
• print(my_file.read())
• my_file.close()
• Example 2:
• my_file = open(“C:/Documents/Python/test.txt”, “w”)
• my_file.write(“Hello World”)
• my_file.close()
Format operator
• argument of write has to be a string, if we want to put other values in a file, we have to convert them to
strings
• Ex:
• x = 52
• fout.write(str(x))
• alternative is to use the format operator %
• For example, the format sequence '%d' means that the second operand should be formatted as a decimal
integer:
• >>> camels = 42
• >>> '%d' % camels
• O/P:'42’
• A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
• 'I have spotted %d camels.' % camels
• O/P:`I have spotted 42 camels.’
• If there is more than one format sequence in the string, the second argument has to be a tuple.
• Each format sequence is matched with an element of the tuple, in order
• >>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels’)
• 'In 3 years I have spotted 0.1 camels. ‘
• '%d' to format an integer, '%g' to format a floating-point number, and '%s' to format a string
• print('The value of pi is: %5.4f' %(3.141592)) # minimum width of 5 and a precision of 4 decimal places.
Format operator
• Number of elements in the tuple has to match the number of format
sequences in the string and the types of the elements have to match
the format sequences
• >>> '%d %d %d' % (1, 2)
• TypeError: not enough arguments for format string
• >>> '%d' % 'dollars’
• TypeError: %d format: a number is required, not str
format() Method

print('a: {a}, b: {b}, c: {c}'.format(a = 1,


b = 'Two',
c = 12.3))
Example:
name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))
Filenames and paths
• Files are organized into directories
• os module provides functions for working with files and directories
• os.getcwd returns the name of the current directory
import os
cwd = os.getcwd()
cwd
• O/P:'C:\\Users\\sagan’- home directory of a user called path
• A simple filename, like memo.txt is also considered a path, but it is a relative
path because it relates to the current directory
• A path that begins with / does not depend on the current directory it is
called an absolute path
• To find the absolute path to a file, you can use os.path.abspath:
• Eg: os.path.abspath('memo.txt')
Catching exceptions
• If you try to open a file that doesn’t exist, you get an FileNotFoundError
• fin = open('bad_file’)
• FileNotFoundError: [Errno 2] No such file or directory: 'bad_file’
• If you don’t have permission to access a file:
• fout = open('/etc/passwd', 'w’)
• PermissionError: [Errno 13] Permission denied: '/etc/passwd’
• If you try to open a directory for reading:
• fin = open('/home’)
• IsADirectoryError: [Errno 21] Is a directory: '/home’
To avoid these errors, try .. Except statement will use. The syntax is similar to an if...else
statement
try:
fin = open('bad_file’)
except:
print('Something went wrong.’)
If an exception occurs, it jumps out of the try clause and runs the except clause.
open the file and read the content to count the
number of lines
f_in=open("input1.txt", "w")
f_in.write("Beautiful is better than ugly.\n Explicit is better than implicit.\n Simple is
better than complex.\n Complex is better than complicated.\n Readability counts.")
f_in.close()
file = open("input1.txt", "r")
count =0
for line in file:
count =count+1

print(count)
file.close()
Write a program to open the file and sort the
content of the file in ascending order
f_in=open("numbers.txt", "w")
f_in.write("123\n4\n98\n34\n34\n2323\n233")
f_in.close()
file = open("numbers.txt", "r")
numbers = []

for line in file:


numbers.append(int(line))

numbers.sort()
print(numbers)
file.close()
Write a program to obtain an integer array and write them to a file
named "input1.txt". Find the maximum and minimum elements.

n =int(input())
f_in=open("input1.txt", "w")
for i in range(0,n):
f_in.write(input())
f_in.write("\n")
f_in.close()
file = open("input1.txt", "r")
numbers = []
for line in file:
numbers.append(int(line))
print(max(numbers))
print(min(numbers))
file.close()

You might also like