oooo
import ram.one.prime as v import ram.two.naturalnumbers as p
p.nat(20) v.primenumbers(99)
---------------- Packages in Python A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. ------------ Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.
Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.
mymodule.py ########## def nat(n): for x in range(1,n): print(x)
def primeornot(n): for x in range(2,int(n/2+1)): if not n%x: return "not Prime" return "prime"
def primeornot1(n): for x in range(2,int(n/2+1)): if not n%x: return False return True def primenumbers(n): for x in range(2,n): if primeornot1(x): print(x)
''' from mymodule import primeornot a=primeornot(8) print (a) '''
import mymodule as n n.primenumbers(100) #print(dir (n))
***********************
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
Example The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py
def print_func( par ): print "Hello : ", par return The import Statement You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax:
import module1[, module2[,... moduleN] When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script −
#!/usr/bin/python
# Import module support import support
# Now you can call defined function that module as follows support.print_func("Zara") When the above code is executed, it produces the following result −
Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.
The from...import Statement Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]] For example, to import the function fibonacci from the module fib, use the following statement −
from fib import fibonacci This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.
The from...import * Statement: It is also possible to import all names from a module into the current namespace by using the following import statement −
from modname import * This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
Locating Modules When you import a module, the Python interpreter searches for the module in the following sequences −
The current directory.
If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable: The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib; And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python Namespaces and Scoping Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python
Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1
print Money AddMoney() print Money The dir( ) Function The dir() built-in function returns a sorted list of strings containing the names defined by a module.
The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −
#!/usr/bin/python
# Import built-in module math import math
content = dir(math)
print content When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.
The globals() and locals() Functions − The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.
The reload() Function When the module is imported into a script, the code in the top-level portion of a module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −
reload(module_name) Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −
reload(hello) Packages in Python A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
#!/usr/bin/python
def Pots(): print "I'm Pots Phone" Similar way, we have another two files having different functions with the same name as above −
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
Phone/__init__.py To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows −
from Pots import Pots from Isdn import Isdn from G3 import G3 After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package. import Phone
Phone.Pots() Phone.Isdn() Phone.G3() When the above code is executed, it produces the following result −
I'm Pots Phone I'm 3G Phone I'm ISDN Phone In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.
############
Sets are lists with no duplicate entries. Let's say you want to collect a list of words used in a paragraph: Sets are a powerful tool in Python since they have the ability to calculate differences and intersections between other sets. For example, say you have a list of participants in events A and B: a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b) To find out which members attended both events, you may use the "intersection" method: a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.intersection(b))
print(b.intersection(a)) ------ To find out which members attended only one of the events, use the "symmetric_difference" method: a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.symmetric_difference(b))
print(b.symmetric_difference(a)) ----------- To find out which members attended only one event and not the other, use the "difference" method: a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.difference(b))
print(b.difference(a)) --------------To receive a list of all participants, use the "union" method: a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.union(b)) ------------ In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B. a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
A = set(a)
B = set(b)
print(A.difference(B))
print(set("my name is Eric and Eric is my name".split()))
aaa
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.
Python Lists The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"] Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −
print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] When the above code is executed, it produces the following result −
list1[0]: physics list2[1:5]: [2, 3, 4, 5] Updating Lists You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : " print list[2] list[2] = 2001; print "New value available at index 2 : " print list[2] Note: append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 : 1997 New value available at index 2 : 2001 Delete List Elements To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1 del list1[2]; print "After deleting value at index 2 : " print list1 When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000] Note: remove() method is discussed in subsequent section.
Basic List Operations Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration Indexing, Slicing, and Matrixes Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections Built-in List Functions & Methods: Python includes the following list functions −
SN Function with Description 1 cmp(list1, list2)
Compares elements of both lists. 2 len(list)
Gives the total length of the list. 3 max(list)
Returns item from the list with max value. 4 min(list)
Returns item from the list with min value. 5 list(seq)
Converts a tuple into list. Python includes following list methods
SN Methods with Description 1 list.append(obj)
Appends object obj to list 2 list.count(obj)
Returns count of how many times obj occurs in list 3 list.extend(seq)
Appends the contents of seq to list 4 list.index(obj)
Returns the lowest index in list that obj appears 5 list.insert(index, obj)
Inserts object obj into list at offset index 6 list.pop(obj=list[-1])
Removes and returns last object or obj from list 7 list.remove(obj)
Removes object obj from list 8 list.reverse()
Reverses objects of list in place 9 list.sort([func])
zzz
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; The empty tuple is written as two parentheses containing nothing −
tup1 = (); To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,); Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Accessing Values in Tuples: To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −
print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", tup2[1:5] When the above code is executed, it produces the following result −
tup1[0]: physics tup2[1:5]: [2, 3, 4, 5] Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python
tup1 = (12, 34.56); tup2 = ('abc', 'xyz');
# Following action is not valid for tuples # tup1[0] = 100;
# So let's create a new tuple as follows tup3 = tup1 + tup2; print tup3 When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz') Delete Tuple Elements Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup del tup; print "After deleting tup : " print tup This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print tup; NameError: name 'tup' is not defined Basic Tuples Operations Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −
Python Expression Results Description len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration Indexing, Slicing, and Matrixes Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −
L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections No Enclosing Delimiters Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz' x, y = 1, 2; print "Value of x , y : ", x,y When the above code is executed, it produces the following result −
abc -4.24e+93 (18+6.6j) xyz Value of x , y : 1 2 Built-in Tuple Functions Python includes the following tuple functions −
SN Function with Description 1 cmp(tuple1, tuple2)
Compares elements of both tuples. 2 len(tuple)
Gives the total length of the tuple. 3 max(tuple)
Returns item from the tuple with max value. 4 min(tuple)
Returns item from the tuple with min value. 5 tuple(seq)
####
def test(a,b): assert a>b, "a must be big than b" try: test(0,20) except AssertionError as e: print (e) ''' When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. '''
aaa
try: sal=open("C:\\Users\\lachu\\Desktop\\sl.txt","r") #print(sal.read()) #sal.seek(0) totalsal=0 for x in sal: totalsal=float(x)+totalsal except ValueError: print("not valid nuber in file") except IOError: print("file not found")
EXCEPTION NAME DESCRIPTION Exception Base class for all exceptions StopIteration Raised when the next() method of an iterator does not point to any object. SystemExit Raised by the sys.exit() function. StandardError Base class for all built-in exceptions except StopIteration and SystemExit. ArithmeticError Base class for all errors that occur for numeric calculation. OverflowError Raised when a calculation exceeds maximum limit for a numeric type. FloatingPointError Raised when a floating point calculation fails. ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. AssertionError Raised in case of failure of the Assert statement. AttributeError Raised in case of failure of attribute reference or assignment. EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. ImportError Raised when an import statement fails. KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. LookupError Base class for all lookup errors. IndexError
KeyError
Raised when an index is not found in a sequence.
Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace. UnboundLocalError
EnvironmentError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
Base class for all exceptions that occur outside the Python environment.
IOError
IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
Raised for operating system-related errors.
SyntaxError
IndentationError
Raised when there is an error in Python syntax.
Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. TypeError Raised when an operation or function is attempted that is invalid for the specified data type. ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. RuntimeError Raised when a generated error does not fall into any category. NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
###############
you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods you should be aware of. ---------------------- When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
Open a file Read or write (perform operation) Close the file --------------------- example ram=open("C:\\Users\\lachu\\Desktop\\venkata.txt","r") print(ram.read(25)) ram.close() """ ram=open("C:\\Users\\lachu\\Desktop\\venka.txt","r") #ram.seek(5) print("file name : ",ram.name) print("file mode : ",ram.mode) print("file close : ",ram.closed) ram.close() print("file close : ",ram.closed) f = open("C:\\Users\\lachu\\Desktop\\venkat.txt","r") print(f.read()) f.close() #C:\\Users\\lachu\\Desktop\\venkat.txt """ --------- Opening a file Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
Python File Modes Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 'x' Open a file for exclusive creation. If the file already exists, the operation fails. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 't' Open in text mode. (default) 'b' Open in binary mode. '+' Open a file for updating (reading and writing) f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods you should be aware of. ---------------------- When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
Open a file Read or write (perform operation) Close the file --------------------- example ram=open("C:\\Users\\lachu\\Desktop\\venkata.txt","r") print(ram.read(25)) ram.close() """ ram=open("C:\\Users\\lachu\\Desktop\\venka.txt","r") #ram.seek(5) print("file name : ",ram.name) print("file mode : ",ram.mode) print("file close : ",ram.closed) ram.close() print("file close : ",ram.closed) f = open("C:\\Users\\lachu\\Desktop\\venkat.txt","r") print(f.read()) f.close() #C:\\Users\\lachu\\Desktop\\venkat.txt """ --------- Opening a file Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
Python File Modes Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 'x' Open a file for exclusive creation. If the file already exists, the operation fails. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 't' Open in text mode. (default) 'b' Open in binary mode. '+' Open a file for updating (reading and writing) f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
#####################
you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods you should be aware of. ---------------------- When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
Open a file Read or write (perform operation) Close the file --------------------- example ram=open("C:\\Users\\lachu\\Desktop\\venkata.txt","r") print(ram.read(25)) ram.close() """ ram=open("C:\\Users\\lachu\\Desktop\\venka.txt","r") #ram.seek(5) print("file name : ",ram.name) print("file mode : ",ram.mode) print("file close : ",ram.closed) ram.close() print("file close : ",ram.closed) f = open("C:\\Users\\lachu\\Desktop\\venkat.txt","r") print(f.read()) f.close() #C:\\Users\\lachu\\Desktop\\venkat.txt """ --------- Opening a file Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
Python File Modes Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 'x' Open a file for exclusive creation. If the file already exists, the operation fails. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 't' Open in text mode. (default) 'b' Open in binary mode. '+' Open a file for updating (reading and writing) f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')