Files
Files
• 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
• 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(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 = []
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()