Start
Entdecken
Suche senden
Hochladen
Einloggen
Registrieren
Anzeige
Anzeige
Anzeige
Nächste SlideShare
Python - An Introduction
Wird geladen in ... 3
1
von
14
Top clipped slide
Python reading and writing files
25. Jan 2016
•
0 gefällt mir
3 gefällt mir
×
Sei der Erste, dem dies gefällt
Mehr anzeigen
•
6,354 Aufrufe
Aufrufe
×
Aufrufe insgesamt
0
Auf Slideshare
0
Aus Einbettungen
0
Anzahl der Einbettungen
0
Jetzt herunterladen
Downloaden Sie, um offline zu lesen
Melden
Software
Python - Reading and Writing Files.
Mukesh Tekwani
Folgen
Author, Online Course Developer, Online Tutor, Learner and Teacher of Physics & Computer Science
Anzeige
Anzeige
Anzeige
Recomendados
Python - An Introduction
Swarit Wadhe
3.1K Aufrufe
•
32 Folien
Functions in python slide share
Devashish Kumar
19K Aufrufe
•
20 Folien
File handling in c
David Livingston J
26.7K Aufrufe
•
34 Folien
Python made easy
Abhishek kumar
4.6K Aufrufe
•
225 Folien
Python
Aashish Jain
1.3K Aufrufe
•
109 Folien
Python basic
Saifuddin Kaijar
10K Aufrufe
•
25 Folien
Más contenido relacionado
Presentaciones para ti
(20)
Python Functions
Mohammed Sikander
•
5.2K Aufrufe
File in c
Prabhu Govind
•
1.8K Aufrufe
Python
Shivam Gupta
•
31.6K Aufrufe
Python and its Applications
Abhijeet Singh
•
10.6K Aufrufe
Python Scipy Numpy
Girish Khanzode
•
4K Aufrufe
Learn 90% of Python in 90 Minutes
Matt Harrison
•
318.7K Aufrufe
Why Python?
Adam Pah
•
1.6K Aufrufe
Python Programming ppt
ismailmrribi
•
2.1K Aufrufe
Python ppt
Anush verma
•
2.2K Aufrufe
Python recursion
Prof. Dr. K. Adisesha
•
289 Aufrufe
File handling in Python
Megha V
•
4.1K Aufrufe
Python : Functions
Emertxe Information Technologies Pvt Ltd
•
3.5K Aufrufe
Python Tutorial Part 2
Haitham El-Ghareeb
•
1.7K Aufrufe
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
•
15.5K Aufrufe
This pointer
Kamal Acharya
•
3.6K Aufrufe
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
•
1.5K Aufrufe
Python Modules
Nitin Reddy Katkam
•
8.4K Aufrufe
Python - the basics
University of Technology
•
5K Aufrufe
NUMPY
SharmilaChidaravalli
•
4.5K Aufrufe
Introduction to python programming
Srinivas Narasegouda
•
1.1K Aufrufe
Similar a Python reading and writing files
(20)
VIT351 Software Development VI Unit5
YOGESH SINGH
•
69 Aufrufe
Python-files
Krishna Nanda
•
105 Aufrufe
Chapter - 5.pptx
MikialeTesfamariam
•
10 Aufrufe
Deletion of a Record from a File - K Karun
Dipayan Sarkar
•
252 Aufrufe
File Handling in C Part I
Arpana Awasthi
•
75 Aufrufe
7 Data File Handling
praveenjigajinni
•
470 Aufrufe
chapter-12-data-file-handling.pdf
study material
•
3 Aufrufe
Data file handling
Prof. Dr. K. Adisesha
•
271 Aufrufe
DFH PDF-converted.pptx
AmitKaur17
•
4 Aufrufe
File Handling In C++(OOPs))
Papu Kumar
•
3.8K Aufrufe
Chapter 08 data file handling
praveenjigajinni
•
23K Aufrufe
Data Science Process.pptx
WidsoulDevil
•
22 Aufrufe
File Handling
AlgeronTongdoTopi
•
1 Aufruf
File Handling
AlgeronTongdoTopi
•
1 Aufruf
File management in C++
apoorvaverma33
•
104 Aufrufe
File handling.pptx
VishuSaini22
•
6 Aufrufe
Python-FileHandling.pptx
Karudaiyar Ganapathy
•
29 Aufrufe
C- language Lecture 8
Hatem Abd El-Salam
•
336 Aufrufe
fileop report
Jason Lu
•
71 Aufrufe
file handling.pdf
RonitVaskar2
•
29 Aufrufe
Anzeige
Más de Mukesh Tekwani
(20)
Circular motion
Mukesh Tekwani
•
558 Aufrufe
Gravitation
Mukesh Tekwani
•
384 Aufrufe
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
•
271 Aufrufe
Hexadecimal to binary conversion
Mukesh Tekwani
•
524 Aufrufe
Hexadecimal to decimal conversion
Mukesh Tekwani
•
260 Aufrufe
Hexadecimal to octal conversion
Mukesh Tekwani
•
345 Aufrufe
Gray code to binary conversion
Mukesh Tekwani
•
232 Aufrufe
What is Gray Code?
Mukesh Tekwani
•
734 Aufrufe
Decimal to Binary conversion
Mukesh Tekwani
•
271 Aufrufe
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
•
211 Aufrufe
Refraction and dispersion of light through a prism
Mukesh Tekwani
•
1.3K Aufrufe
Refraction of light at a plane surface
Mukesh Tekwani
•
1.4K Aufrufe
Spherical mirrors
Mukesh Tekwani
•
217 Aufrufe
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
•
491 Aufrufe
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
•
1.1K Aufrufe
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
•
124 Aufrufe
Cyber Laws
Mukesh Tekwani
•
484 Aufrufe
XML
Mukesh Tekwani
•
367 Aufrufe
Social media
Mukesh Tekwani
•
397 Aufrufe
TCP-IP Reference Model
Mukesh Tekwani
•
955 Aufrufe
Último
(20)
PPT-UEU-Basis-Data-Pertemuan-1.pptx
UbaidURRahman78
•
1 Aufruf
0x01 - Breaking into Linux VMs for Fun and Profit
Russell Sanford
•
13 Aufrufe
Firewalls (1).ppt
adnanetnzr
•
1 Aufruf
How to export EML files into Outlook PST formats?
MailsDaddy
•
0 Aufrufe
Healthcare Mobile App Development Trends in 2023.pdf
Seasia Infotech
•
0 Aufrufe
Visual programming.ppt
DawoudIssa
•
5 Aufrufe
pmk.docx
fairy70
•
3 Aufrufe
reverse engineering.pptx
alishahid244986
•
1 Aufruf
Fansportiz - Fantasy Sports app development company
Fansportiz - Fantasy Sports app development company
•
2 Aufrufe
Growth Strategy
Prasanna Hegde
•
3 Aufrufe
Exploring Generating AI with Diffusion Models
KonfHubTechConferenc
•
142 Aufrufe
Transforming Healthcare: The Role of CMMS in Hospital Facility Maintenance an...
Srinivasan AT
•
4 Aufrufe
CREATION AND DETECTION OF QR CODE.pptx
ELECTRONICSCOMMUNICA6
•
2 Aufrufe
Some benefits of hiring Offshore Development Team.pdf
Go-Tech Solution
•
5 Aufrufe
Hotel GDS
ChetnaPatil34
•
3 Aufrufe
Production-ready GraphQL with Caliban
Pierre Ricadat
•
4 Aufrufe
Zethic’s Basics of App Development - Step-by-Step Guide.pdf
Zethic
•
5 Aufrufe
ISTQB-CTFL_Syllabus_2018_v3.1.1 (1).pdf
D19CQVT01NTATHIMAILI
•
4 Aufrufe
SE_RE-II-CH5 (3).pdf
AZKANAAZ1
•
3 Aufrufe
Are you ready for AI? Is AI ready for you?
KonfHubTechConferenc
•
47 Aufrufe
Anzeige
Python reading and writing files
© Prof Mukesh N Tekwani, 2016 Unit I Chap 1 : Python File Input and Output I.1 Concept of a File: In all the
programs we have seen so far, the data provided to a Python program was through the command line and it is not saved. If a program has to be run again, the user must again input data. Similarly, the output of a program appears on the computer screen but is not saved anywhere permanently. In practical programming it is necessary to provide data to a program from a file, and save the output data into a file. The output data may be required for further processing. A file is a collection of data. This data may be, for example, students’ data (Roll No, Name, Address, Tel No, Grades,...), employee data (EmpID, Name, Dept, Designation, Salary…), etc. A file could also be used to store a picture (say the fingerprints of employees), audio, video, etc. I.2 Types of Files: There are many different types of files. (i) Text files (ii) audio files (iii) video files (iv) binary files (v) presentations (Microsoft PowerPoint presentation .pptx files) (vi) Word processor documents (Microsoft Word .docx files), etc In this chapter we will study how Python handles text files. Text files contain only text characters (alphabets, digits, mathematical symbols, and other readable characters.A text file can be created and opened in any text editor such as Notepad. Text inside a text file cannot be formatted such as bold, italic, underline, font colors, styles etc. These files donot contain any metadata such as page numbers, header, footer, etc. But text files are very useful as they can store data which can be imported into various types of programs. Text files are small in size and therefore easier and faster to process. Some examples of text files are: files created with text editor such as Notepad, programs in programming languages such as Python, C, C++, etc, HTML files, CSV files, etc. CSV stands for Comma Separated Value. In a CSV file, data is separated by using a comma between different items. For example, a CSV text file containing student data looks like this: Name, Class, MajorSubject, Grade Amit, FYBSc, Physics, 1 Nikhil, SYBCom, Accounts, 1 Prerana, TYBSc, Chemistry, 2 1
© Prof Mukesh N Tekwani, 2016 In this chapter
we will study how to write Python programs that use text files to input and output data. I.3 Opening a file: For this exercise, create a folder called in C drive called: C:/37/Files. We will save all our programs for this chapter in this folder. In IDLE (Integrated Development and Learning Environment), select File → New File and type the following three lines: This is Line 1 This is Line 2 This is Line 3 Save this file as a text file with filename FileEx1.txt, in the folder you just created. Create a new program file in IDLE and save it with the filename FileReader1.py. This file should also be saved in the folder C:37Files Program 1: FileReader1.py file = open("C:/37/files/FileEx1.txt", "r") contents = file.read() print(contents) file.close() Run this program and the output is as shown below: This is Line 1 This is Line 2 This is Line 3 Analysis of the program: 1. open() is a builtin function in Python. It opens a file; the file cursor is used to keep information about the current location in the file, which part of the file has been read, and which part has yet to be read. Initially, the file cursor points to the beginning of the file but as we read the file, the file cursor begins to move forward. 2. The first argument in the function open() is "C:/37/files/FileEx1.txt". It is the name of the file to open. The second argument is “r”, which means that the file has to be opened in readonly mode. Here, “r” is called as the file mode. Other file modes are “w” for writing to a file and “a” to append data to a file. If file mode is omitted in the function call, it is assumed to be “read only”. 3. The second statement file.read() tells Python that you want to read the contents of the entire file into a string called contents. 4. The third statement print(contents), prints the string. 2
© Prof Mukesh N Tekwani, 2016 5. The last statement is file.close(). It closes the file. Every file opened for reading/writing must be closed. The with statement: Every open file must be closed in Python. So we have to use two statements in every program like this: file = open(filename, mode) : : : file.close() In this
code, the name file is a file handle. Python provides the with statement that automatically closes a file when the end of the file is reached. General syntax: with open(filename, mode) as variable: processing block The complete program to read a text file is now : Program 2: FileReader2.py with open("C:/37/files/FileEx1.txt", "r") as file: contents = file.read() print(contents) Output of the above program is the same as that for FileReader1.py I.4 Techniques for Reading Files: There are four techniques for reading a file and all these techniques work by starting at the current file cursor. 1. Techniques for Reading a File : “The Read Technique”: This techniques is used to: (i) Read the contents of a file into a single string, or (ii) To specify exactly how many characters to read. To read the contents of the file into a single string, we use the following syntax: while open(filename, mode) as file: contents = file.read() print (contents) 3
© Prof Mukesh N Tekwani, 2016 This reads the
entire file from the current cursor location to the end of the file, and then moves the cursor to the end of the file. To read a specific number of characters, we specify the number of characters to read as the argument to the read() function. For example, to read 10 characters from the beginning of the file, the program is: Program 3: file = open("C:/37/files/FileEx1.txt", "r") contents = file.read(10) print(contents) file.close() The output of this program for the same input as shown below: This is Li >>> The cursor now points to the character after the 10th character. 2. Techniques for Reading a File: “The Readlines Technique”: This technique is used to read each line of a text file and store it in a separate string. After reading the lines, the cursor moves to the end of the file. Program 4: FileReader5.py # Read the lines of a file into separate strings print ("This program reads the lines of a file into separate strings .") with open("C:/37/files/FileEx1.txt", "r") as file: lines = file.readlines() print(lines) In this program, the statement print(lines) prints all the strings. Output of this program is : This program reads the lines of a file into separate strings . ['This is Line 1n', 'This is Line 2n', 'This is Line 3n'] >>> Each line ends with the newline character ‘n’ . But the last line of a text file may not end with a ‘n’ character. To print only line no 2, we can modify the program as follows: Program 5: # Read the lines of a file into separate strings print ("This program reads the lines of a file into separate strings and prints only the 4
© Prof Mukesh N Tekwani, 2016 second line.") with open("C:/37/files/FileEx1.txt", "r") as file: lines = file.readlines() print(lines[1]) file.close() In the above
program, the line print(lines[1]) prints only the 2nd line. Remember, indices start at 0. What happens when we give an index number more than the number of lines? Try this statement: print(lines[10]). Now, we get an error as shown below This program reads the lines of a file into separate strings and prints only the second line. Traceback (most recent call last): File "C:/37/files/FileReader5.py", line 6, in <module> print(lines[10]) IndexError: list index out of range >>> Program 6: FileReader6.py This program prints the lines of a text file in reverse order. # Read the lines of a file into separate strings # Then print the lines in reverse order print ("This program reads the lines of a file into separate strings and prints them in reverse order.") with open("C:/37/files/FileEx2.txt", "r") as file: lines = file.readlines() print(lines) for site in reversed(lines): print(site.strip()) file.close() Assume the file FileEx2.txt contains the following lines: Google Microsoft IBM Infosys Wipro Capgemini This program reads the lines of a file into separate strings and prints them in reverse order. ['Googlen', 'Microsoftn', 'IBMn', 'Infosysn', 'Wipron', 'Capgeminin'] Capgemini 5
© Prof Mukesh N Tekwani, 2016 Wipro Infosys IBM Microsoft Google >>> Analysis: We have
used the builtin function reversed() to reverse the items in the list. The strip() method is used to remove all whitespace characters from the left and right of a string. We have used the strip() method without any arguments so it removes only whitespaces. To remove whitespace characters only from the left of a string use the method lstrip(). To remove whitespace characters only from the right of a string use the method rstrip(). Run the following program and comment on the output: Program 7: FileReader7.py Using the strip() method. # Read the lines of a file into separate strings # Then print the lines in reverse order print ("This program reads the lines of a file into separate strings and prints them in reverse order. What is the output? What happened to the ‘C’? Why is there a blank line between two lines in the o/p?") with open("C:/37/files/FileEx2.txt", "r") as file: lines = file.readlines() print(lines) for site in reversed(lines): print(site.strip('C')) file.close() Why is there a blank line between two lines? Program 8: FileReader8.py Program to sort the lines of a text file. # Read the lines of a file into separate strings # Then print the lines in sorted order print ("This program reads the lines of a file into separate strings and prints them in sorted order.") with open("C:/37/files/FileEx2.txt", "r") as file: lines = file.readlines() 6
© Prof Mukesh N Tekwani, 2016 print("Original lines:") print(lines) print("Lines in sorted order:") for site in sorted(lines): print(site.strip()) file.close() The builtin
function sorted() is used to sort the lines and display them. Note that, there is no change made to the original text file. 3. Techniques for Reading a File : “The For Line In File” Technique: This techniques is used to carry out the same action on each line of a file. Suppose we want to read a text file and print the length of each line i.e. number of characters in each line. Here is the program Program 9: FileReader9.py Program to print the length of each line of a text file. # Read the lines of a file order and print the length of each line print ("This program reads the lines of a file and prints the length of each line.") with open("C:/37/files/FileEx2.txt", "r") as file: for line in file: print(line, len(line)) file.close() Output of this program is : This program reads the lines of a file and prints the length of each line. Google 7 Microsoft 10 IBM 4 Infosys 8 Wipro 6 Capgemini 10 >>> 7
© Prof Mukesh N Tekwani, 2016 Observe that the
length of each string is one more than the number of characters that can be seen. But each string is terminated by the newline character ‘n’ so that increases the size by one character. Modification: Make only this small change in the program and observe the output: print(line.strip(), len(line)) What is the output and why is it like that? Modification: No modify the print line as follows and comment on the output: print(line, len(line.strip())) 4. Techniques for Reading a File : “The Readline” Technique: This techniques is used to read one entire line from a file. This line can then be processed. Program 10: FileReader10.py Program to illustrate the use of readline() technique. A text file contains the following data about number of students in various academic years in FYBSc. Filename: FileEx3.txt Number of students in various academic years in FYBSc #Year 201011 to 201516 #Semester 1 67 69 53 58 66 61 We have to count the total number of students in these academic years, with open("C:/37/files/FileEx3.txt", "r") as inpfile: #Read the description line file.readline() #Keep reading the comment lines until we read the first piece of data data = inpfile.readline().strip() while data.startswith("#"): data = inpfile.readline().strip() #Now we have the first actual data item. Add it to total number of students numofstudents = int(data) #Read the rest of the file for data in inpfile: 8
© Prof Mukesh N Tekwani, 2016 numofstudents = numofstudents + int(data) print("Total number of students: ", numofstudents) I.5 Techniques for Writing Files: The builtin write() function is used to write data to a text file. The general syntax of write() is: file.write(string) The following
program opens a file called FileEx4.txt and writes the words “I Love Python” to the file and then closes the file. Program 11: FileReader11.py Program to write a string to a text file. #Writing a file with open("C:/37/files/FileEx4.txt", "w") as optfile: optfile.write("I Love Python") optfile.close() The file is now opened in write mode by using “w” as the mode. If the file FileEx4.txt already exists, it is overwritten with new data.If the filename does not exist, it is first created and then data written to it. Program 12: FileReader12.py Program to write a the numbers 1 to 10, one per line to a text file. #Writing the numbers 1 to 10 to a file with open("C:/37/files/FileEx5.txt", "w") as optfile: for i in range(1, 11): optfile.write(str(i)+ "n") optfile.close() Check the output of the file FileEx5.txt by opening it in a text editor. Program 13: FileReader13.py Program to append data to a text file. The following program appends numbers from 11 to 20 to the file FileEx5.txt that we created earlier. Data already stored in the file is not lost, and new data is added to the end of the file FileEx5.txt 9
© Prof Mukesh N Tekwani, 2016 #Appending data to a file with open("C:/37/files/FileEx5.txt", "a") as optfile: for i in range(11, 21): optfile.write(str(i)+ "n") optfile.close() Program 14: FileReader14.py Program to read data from a file, process it and write it to another file. A file
FileEx6.txt contains the marks obtained by 5 students in two tests. These marks are separated by a blank space. Write a program that reads the two marks for each student and stores these marks and their total in another file called Results.txt FileEx6.txt Results.txt 15 18 17 22 6 11 21 25 23 22 M1 M2 Total 15 18 33 17 22 39 6 11 17 21 25 46 23 22 45 Program: # Read the contents of a file, process each line and write results to a new file print("Read the contents of a file, process the data and write result into another file") optfile = open("C:/37/files/Results.txt", "w") inpfile = open("C:/37/files/FileEx6.txt", "r") optfile.write("M1 M2 Totaln") for numpair in inpfile: numpair = numpair.strip() values = numpair.split() total = int(values[0]) + int(values[1]) optline = '{0} {1}n'.format(numpair, total) optfile.write(optline) print("file written") print("now closing all files") optfile.close() inpfile.close() 10
© Prof Mukesh N Tekwani, 2016 Program 15: FileReader15.py Program to prompt the user for a file and display the contents of the file. #To prompt the user for a filename and display the contents of that file name = input("Enter the file name ") fname = open(name, "r") print("Contents of the file are : ") contents = fname.read() print(contents) fname.close() Program 16: FileReader16.py Program to prompt the user for a filename and backup the file. # Write a program that makes a backup copy of your file #import the module os so that we can use functions from this module import os orgfile = input('Which file would you like to backup? ') base, ext = os.path.splitext(orgfile) #print (base) #print(ext) new_filename = base + '.bak' backup = open(new_filename, 'w') orgfile = open(orgfile, "r") for line in orgfile: backup.write(line) orgfile.close() backup.close() I.6 Manipulating Directories: Files are arranged
in folders or directories. Every running program has a “current directory”. Python searches for files in the default or current directory. Python has a module named os module which contains many functions for working with files and directories. We now study some of these builtin functions of the os module. 11
© Prof Mukesh N Tekwani, 2016 Program 17: FileReader17.py Program to study directory manipulation. #Import the module os import os #Get the current working directory or relative path cwd = os.getcwd() print("Current working directory: ", cwd) #To get the absolute path names print("Absolute path: ", os.path.abspath('Results.txt')) #To check if a file or directory exists print("Does file exist: ", os.path.exists("Results.txt")) print("Does file exist: ", os.path.exists("Results.xls")) #To check if it is a directory print("Is it a directry: ", os.path.isdir("Results.txt")) print("Is it a directry: ", os.path.isdir("C:37files")) #To check if it is a file print("Is it a file: ", os.path.isfile("Results.txt")) #To return a list of files and directories in a directory print("List of files and sub directories: ") print(os.listdir(cwd)) Practical Exercises 1. Write a
program to ignore the first 10 characters of a text file and print the remaining characters. 2. Write a program that prompts the user for a file to display and then show the contents of the file. 3. Write a program that makes a backup of a file. Your program should prompt the user for a file to copy and then write a new file with the same contents but with .bak as the file extension. 4. Write a program that prints the length of each line in a text file. 5. Develop a Python program that reads in any given text file and displays the number of lines, words and total number of characters in the file including spaces and special characters but not the newline character ‘n’. 6. Develop a Python program that reads messages contained in a text file, and encodes the messages saved in a new file. For encoding messages, a simple substitution key should be used as shown : A>C, B → D, C → E, D → F, … etc. The unencrypted text file has the filename msgs.txt and the encrypted file has the same name but filename extension is .enc 7. Develop a Python program that reads encrypted messages contained in a text file, and decodes the messages saved in a new file. For decoding messages, a simple substitution key should be used as shown : CA, D → B, E→ C, F→ D, … etc. The 12
© Prof Mukesh N Tekwani, 2016 encrypted text file
has the filename msgs.enc and the decrypted file has the same name but filename extension is .txt 8. Write a Python program that reads a text file and prints each word on a separate line. 9. A text file called marks contains the marks obtained by 20 students. Assume marks are not repeated. Write a Python program to find and display the highest mark. 10. Write a program that reads the first 10 characters of a text file but does not display them. The rest of the characters should be displayed, 11. Write a program that prints the length of each line. The output should have this format: Line No Length 1 2 : 12. What is the output of the following program? f = None for i in range (5): with open("data1.txt", "w") as f: if i > 2: break print (f.closed) g = open("data2.txt", "w") for i in range (5): if i > 2: break print (g.closed) 13
© Prof Mukesh N Tekwani, 2016 Miscellaneous Questions 1. Give an
instruction in Python that opens a file named “Markss.txt” for reading and assigns the identifier inpfile to the file object created. 2. Give an instruction in Python that opens a file named “Results.txt” for writing and assigns the identifier optfile to the file object created. 3. Multiple Choice Questions: 3.1. Which of the following statements are true? (multiple answers allowed) a) A. When you open a file for reading, if the file does not exist, an error occurs. b) When you open a file for reading, if the file does not exist, the program will open an empty file. c) When you open a file for writing, if the file does not exist, a new file is created. d) When you open a file for writing, if the file exists, the existing file is overwritten with the new file. Ans a, c, d 14
Anzeige