DATA FILES IN PYTHON

2y ago
26 Views
2 Downloads
1.22 MB
13 Pages
Last View : 30d ago
Last Download : 3m ago
Upload by : Joanna Keil
Transcription

DATA FILES IN PYTHONWHY DATA FILES ?As we know whenever we enter data while running programs, it is not savedanywhere and we have to enter it again when we run the program again. So tostore required data permanently on hard disk (Secondary Storage Device) weneed to store it in File.Note : File is a Stream or sequence of bytes /charactersPython Data Files can be of two types1. Text File (By default it creates file in text Mode2. Binary FileDifference between Text and Binary FilesS.No.Python Text FilePython Binary Files1.Consists Data in ASCII (Human readableform.Consists Data in Binary form2.Suitable to store Unicode characters also Suitable to store binary data such asimages, video files , audio files etc.3.Each line in Text file is terminated with aSpecial character EOL(end of line)There is no EOL character4.Operation on text files are slower thanbinary files as data is to be translated tobinaryOperation on binary files are faster asno translation requiredOperations on File:1. How to Handle Data File/ Text File:Whenever we worked with Data File in Python we have to follow sequence1.1 Open/Create File1.2 Read from/Write to file1.3 Close File1https://pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

We can do following tasks/operations with python Data File.a)b)c)d)e)f)g)h)Creation/Opening of an existing Data FileReading from fileWriting to Data FileAppending data ( inserting Data at the end of the file)Inserting data (in between the file)Deleting Data from fileCopying a fileModification/Updation in Data File.Functions Used for File Handlings.no Function.Name1open()SyntaxUseF obj open(“File name”To Open or create a file indesired modeTo Close the file,mode)2closeF obj.close()3read()4readline()5readlines()F obj.read() orF obj.read(n)F obj.readline() orF obj.readline(n)F obj.readlines()6write()F obj.write(str)7writelines()F obj.writelines(LST)To read all or specified no. ofcharacters from fileTo read a single line orspecified no. of charactersfroma linein a fileToreadall linesfrom a fileand returns it in the form oflistwrite data (of string type)Toon to the fileTo Write Sequence (list/tupleetc) of strings in a fileBefore discussing reading and writing operation let’s understand theFile Modes. Consider the table of modes given below.2https://pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Here is a list of the different modes of opening a file Sr.No.Modes & Description1rOpens a file for reading only. The file pointer is placed at the beginning of thefile. This is the default mode.2rbOpens a file for reading only in binary format. The file pointer is placed at thebeginning of the file. This is the default mode.3r Opens a file for both reading and writing. The file pointer placed at thebeginning of the file.4rb Opens a file for both reading and writing in binary format. The file pointerplaced at the beginning of the file.5wOpens a file for writing only. Overwrites the file if the file exists. If the filedoes not exist, creates a new file for writing.6wbOpens a file for writing only in binary format. Overwrites the file if the fileexists. If the file does not exist, creates a new file for writing.7w Opens a file for both writing and reading. Overwrites the existing file if the fileexists. If the file does not exist, creates a new file for reading and writing.8wb Opens a file for both writing and reading in binary format. Overwrites theexisting file if the file exists. If the file does not exist, creates a new file forreading and writing.aOpens a file for appending. The file pointer is at the end of the file if the fileexists. That is, the file is in the append mode. If the file does not exist, itcreates a new file for writing.910abOpens a file for appending in binary format. The file pointer is at the end ofthe file if the file exists. That is, the file is in the append mode. If the file doesnot exist, it creates a new file for writing.a Opens a file for both appending and reading. The file pointer is at the end ofthe file if the file exists. The file opens in the append mode. If the file does notexist, it creates a new file for reading and writing.ab Opens a file for both appending and reading in binary format. The file pointeris at the end of the file if the file exists. The file opens in the append mode. Ifthe file does not exist, it creates a new file for reading and s.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Let’s understand the read Operation.Look at the following Two Screen shots (1st is Showing Code whereas 2nd isshowing different outputs) where comparison among different type of readoperation have shown. Here you find comparison among read(),readline() andreadlines() functions .Screenshot 1ShowingCode withdifferenttypes ofreadoperationScreenshot 2ShowingOutput ofdifferenttypes press.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

CODINGf open("mydat.txt","r")contents f.read()print(contents)f.close()f open("mydat.txt","r")contents f.read(70)print(contents)f.close()f open("mydat.txt","r")contents f.readline()print(contents)f.close()f open("mydat.txt","r")contents f.readline(60)print(contents)f.close()OUTPUT & EXPLAINATIONLook, it read all the characters from the filemydat.txtHere it has read first 70 characters from the filemydat.txtHere it has read Only first linefrom the file mydat.txtHere it has read first 60 characters from the firstline of the file mydat.txtf open("mydat.txt","r")contents f.readlines()print(contents)f.close()Here it has read all the lines from the file om by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Now let’s discuss write Operation on fileLook at the following Two Screen shots (1st is Showing Code whereas 2nd isshowing different outputs) where comparison among different type of writeoperations have shown. Here you find comparison between write(),writeline(),In the above code we have created 4 different files namely Nw File1.txt,Nw File2.txt, Nw File3.txt, Nw File4.txt.Case 16In the Nw File1.txtwe are writing Stringwith write() function.See the outputhttps://pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

In the Nw File2.txtwe have wrote list ofString without \nusing writelines()functionCase 2In the Nw File3.txt wehave wrote list of Stringwith\n using write()functionCase 3In the Nw File4.txt wehave wrote tuple ofStrings with \n Stringusing write() functionCase 4In the previous cases whenever we run the code again previously writtencontents will be overwritten. If we want to add contents after thepreviously added contents then we need to open file in append mode.See Example wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Output of the above codeNow reading the contents of file created by above codeFile : “filereadapp.py”Output will beNow If we Run the file “fileappend.py” again it will add new records after thepreviously added records.Have a look ,(This time we are adding 3 m by Sangeeta M Chauhan , PGT CS, KV3Gwalior

After running the “Filereadapp.py” again, Output will be2. Binary Files in PythonWhy Binary Files ?Since binary files store data after converting it into binary language(0s and 1s), there is no EOL character. This file type returns bytes.This is the file to be used when dealing with non-text files such asimages or exe.2.1 Reading and Writing list from/to binary fileCase 1: Writing list on Binary Filelist1 [23, 43, 55, 10, 90]newFile open("binaryFile", "wb")newFile.write(bytearray(list1))Conversion of list into bytes iary.wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Case 2: Reading list from binary FilenewFile open("binaryFile", "rb")list1 list(newFile.read())Conversion of binary data into list isrequirednewFile.close()print(list1)2.2 Reading and Writing pdf file from/to binary filefile open("NewXI1.pdf", "wb")# file to write tofile2 open("ComputerSc NewXI.pdf", "rb") # file to read frombin cont file2.read()file.write(bin cont)file.close()file2.close()Above Code will make another copy of ComputerSc NewXI.pdf withnew name NewXI1.pdf2.3 Reading and Writing image file from/to binary filefile1 open("TREE.jpg", "rb") # file to read fromfile2 open("Nw TREE.jpg", "wb") # file to write tobin cont file1.read()file2.write(bin ssroomdiary.wordpress.com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Above Code will make another copy of ComputerSc NewXI.pdf withnew name NewXI1.pdfAbove Code will make another copy of image file TREE.jpg with new nameNw TREE.jpg2.3 Reading and Writing Sequences(Dictionary, lists etc) withmixed data type from/to binary fileTo write mixed type of Data we need to import Pickle module. Picklingmeans converting structure into byte stream before writing the datainto fileIts two main methods are:1. pickle .dump() : To write the Object into the fileSyntax : pickle.dump(object to write,file object)2. pickle .load() : To read the Object from the fileSyntax : container obj pickle.load(file object)Lets Understand it more clearly through examplesCase 1: To Write /Read .com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Case 2: To Write /Read DictionaryOutputCase 3: To Write /Read Two different om12OutputGwaliorby Sangeeta M Chauhan , PGT CS, KV3

3. ABSOLUTE AND RELATIVE PATHS We all know that the when we create python files, they are kept indefault directory which are also known as folders. At the time of Program run Python searches current(default)directory.Path : is the general form of the name of a file or directory, specifies aunique location in a file systemRelative Path : A relative path defines a location that is relative to thecurrent directory or folder. For example, the relative path toa file named "MyFile.txt" located in the current directory is simply thefilename, or "MyFile.txt"Absolute Path : An absolute path refers to the complete detailsneeded to locate a file or folder, starting from the root element andending with the other subdirectoriesIf we want to know the Current Working Directory We have OS module(Operating System )which provides many such functions which can be usedto work with files and directories and a function getcwd( ) function can beused to identify the current working directory like this : import os curr dir os.getcwd() print(curr dir)Output C:\Users\Sangeeta . Standard FileStreamsstandard streams are preconnected input and output communicationchannels between a computer program and its environment when it beginsexecution.The three input/output (I/O) connections/Streams are :i. Standard input (stdin), sys.stdin (read from standard input)ii. Standard output(stdout) sys.stdout (Write to Standard Output Device)iii. Standard error (stderr). sys.stderr (Contains Error com by Sangeeta M Chauhan , PGT CS, KV3Gwalior

Consists Data in Binary form 2. Suitable to store Unicode characters also Suitable to store binary data such as images, video files , audio files etc. 3. Each line in Text file is terminated with a Special character EOL(end of line) There is no EOL character 4. Operation on text files are slower than binary files as data is to be translated to

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

The Monty Python : œuvres (62 ressources dans data.bnf.fr) Œuvres audiovisuelles (y compris radio) (20) Monty Python live (mostly) (2014) Monty Python live (mostly) (2014) Monty Python live (mostly) (2014) "Monty Python, almost the truth" (2014) de Alan Parker et autre(s) avec The Monty Python comme Acteur "Monty Python, almost the truth" (2014)

Introduction to basic Python Contents 1. Installing Python 2. How to run Python code 3. How to write Python code 4. How to troubleshoot Python code 5. Where to go to learn more Python is an astronomer's secret weapon. With Python, the process of visualizing, processing, and interacting with data is made extremely simple.

A Python Book A Python Book: Beginning Python, Advanced Python, and Python Exercises Author: Dave Kuhlman Contact: dkuhlman@davekuhlman.org