Python Programming 19CSE282

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Python Programming

19CSE282
What You Need In Order To Read
Informa4on From A File
1.  Open the file and associate the file with a file
variable.
2.  A command to read the informa4on.
3.  A command to close the file.
1. Opening Files
Prepares the file for reading:
A.  Links the file variable with the physical file (references to the file variable are
references to the physical file).
B.  Posi4ons the file pointer at the start of the file.
Format:1
<file variable> = open(<file name>, "r")
fhand = open(‘test’, “r”)

Example:
(Constant file name)
inputFile = open("data.txt", "r")
OR
(Variable file name: entered by user at run4me)
filename = input("Enter name of input file: ")
inputFile = open(filename, "r")

1 Examples assume that the file is in the same directory/folder as the Python program.
2. Reading Informa4on From Files
•  Typically reading is done within the body of a loop
•  Each execu4on of the loop will read a line from the file into
a string
Print(fhand.readline())
Format:
for <variable to store a string> in <name of file variable>:
<Do something with the string read from file>

Example:
for line in inputFile:
print(line) # Echo file contents back onscreen
Closing The File
•  Although a file is automa4cally closed when your program
ends it is s4ll a good style to explicitly close your file as soon
as the program is done with it.
•  What if the program encounters a run4me error and crashes before
it reaches the end? The input file may remain ‘locked’ an
inaccessible state because it’s s4ll open.
•  Format:
<name of file variable>.close()

•  Example:
inputFile.close()
Reading From Files: PuTng It All
Together
Name of the online example: grades1.py
Input files: letters.txt or gpa.txt

inputFileName = input("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")

for line in inputFile:
sys.stdout.write(line)


inputFile.close()
print("Completed reading of file", inputFileName)
What You Need To Write
Informa4on To A File
1.  Open the file and associate the file with a file
variable (file is “locked” for wri4ng).
2.  A command to write the informa4on.
3.  A command to close the file.
1. Opening The File
Format1:
<name of file variable> = open(<file name>, "w")

Example:
(Constant file name)
outputFile = open("gpa.txt", "w")

(Variable file name: entered by user at run4me)
outputFileName = input("Enter the name of the output file
to record the GPA's to: ")
outputFile = open(outputFileName, "w")

1 Typically the file is created in the same directory/folder as the Python program.
3. Wri4ng To A File
•  You can use the ‘write()’ func4on in conjunc4on with a file variable.
•  Note however that this func4on will ONLY take a string parameter
(everything else must be converted to this type first).

Format:
outputFile.write(temp)

Example:
# Assume that temp contains a string of characters.
outputFile.write (temp)
Wri4ng To A File: PuTng It All Together
• Name of the online example: grades2.py
• Input file: “letters.txt” (sample output file name: gpa.txt)

inputFileName = input("Enter the name of input file to read the

grades from: ")

outputFileName = input("Enter the name of the output file to

record the GPA's to: ")

inputFile = open(inputFileName, "r")


outputFile = open(outputFileName, "w")

print("Opening file", inputFileName, " for reading.")

print("Opening file", outputFileName, " for writing.")


gpa = 0
Wri4ng To A File: PuTng It All Together (2)
for line in inputFile:
temp = str (gpa)
if (line[0] == "A"): temp = temp + '\n'
gpa = 4 print (line[0], '\t', gpa)
outputFile.write (temp)
elif (line[0] == "B"):
gpa = 3
elif (line[0] == "C"):
gpa = 2
elif (line[0] == "D"):
gpa = 1
elif (line[0] == "F"):
gpa = 0
else:
gpa = -1

Wri4ng To A File: PuTng It All
Together (3)
inputFile.close ()
outputFile.close ()
print ("Completed reading of file", inputFileName)
print ("Completed writing to file", outputFileName)
Arrays
•  Array is a data structure that stores value of same data
type.
•  The difference between array and list:
Python list -> different data types
Python Array -> same data type
•  Python does not have built in support for arrays
•  Python lists can be used
•  Module = ‘Array’ -> import array
Crea4ng array
array(data type, value list)
Example:
import array
arr = array.array('i', [1, 2, 3])
To print:
for i in range(0,len(arr),):
print(arr[i])

To add element at the end of the array
arr.append(4)

To add element at the specific index
arr.insert(2, 10)

pop() -> This func4on removes the element at the posi;on men4oned in its argument, and returns it.

arr.pop(2)

remove() -> This func4on is used to remove the first occurrence of the value men4oned in its
arguments.
arr.append(1)
arr.remove(1)
Anonymous Func:ons
•  Not declared using def keyword
•  Lambda keyword – To create small anonymous func4on
•  Can take any number of arguments. But can have only one
expression
•  Syntax:
lambda arguments:expression
•  Example
res = lambda a : a+100
print(type(res)) -- > <class ‘func4on’>
print(res(240))

Write a program to square and cube every
number in a given list of integers using lambda
func4on.



Sample Input 1
1 2 3 4 5 6 7 8 9 10
Sample Output 1
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]


inp_list = [1,2,3,4,5,6,7,8,9]

square_nums = list(map(lambda x: x ** 2, inp_list))

cube_nums = list(map(lambda x: x ** 3, inp_list))



print(square_nums)

print(cube_nums)

You might also like