Lab9 Files

You might also like

Download as pdf
Download as pdf
You are on page 1of 2
sa1aro019 Labo lab9 : Files What is file? File is a named location on disk to store related information. It is used to per manently store data in a non-volatile memory (e.g. hard disk). File type Python can handel multipl type of files such as txt, csv, In this section we will handel text file. method 1- open) 2+ write() 3+ close() more in the picture open() - A function that handel files and takes two parameters; filename, and mode. - Modes: - Read - Default value. Opens a file for reading, error if the file does no t exist = Append - Append to the end of the file, creates the file if it does not e xist Write - Opens a file for writing, creates the file if it does not exist Create - Creates the specified file, returns an error if the file exists Text + Default value. Text mode "b" - Binary - Binary mode (e.g. images) - syntax open(‘file.txt', 'w") Delete files import os os.remove("File. txt") Exercises {ile INC:/Users/Basma/Desktop/Labo flesh! 1 sa1aro019 Labo Create an empty text file in Desktop then rename it to file1 then write a python code that open the file and write to the file the sentence ‘Hello, python’ In [3]: #1 = open(*C:\\Users\\Basma\\Desktop\\file1.txt",'w') f1.write('Hello, python’) f1.close() Write a python program that do the following: “Create text file with name data slirite to files student name with information with groups file will contain Ahmed 2001 m marwa 2002 f mena 2002 £ Ali 2001 m Dina 2001 £ mina 2000 m = Count number of all student, number of student, male and female and disply the se numbers In [12]: 2 = open(‘data. txt’, ‘w") f2.write("Ahmed 2001 m\nmarwa 2002 f\nmena 2002 f\nAli 2001 m\nDina 2001 f\nmina 2000 m \n') 2.close() In [17]: count_std count_f = 0 count_n=0 #3 = open(‘data.txt") for lin in #3: count_std + if Lin.endswith(‘m\n'): count_m += 1 elif Lin.endswith('f\n"): count_f +=1 #3.close() print('student: ', count_std, ‘Female:',count_f, ‘Male:', count_n) student: 6 Female: 3 Male: 3 In[ ]: {ile INC:/Users/Basma/Desktop/Labo flesh! 22

You might also like