You are on page 1of 19

UNIT – I

Section A
Computational Thinking & Programming – 2

Python
It is a widely used general purpose, high level programming language. Developed by Guido
van Rossum in 1991. It is used for: software development, web development (server-side),
system scripting, Mathematics.

Features of Python
1. Easy to use – Due to simple syntax rule
2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on Windows, Linux, Macintosh etc. equally
4. Expressive language – Less code to be written as it itself express the purpose of the
code.
5. Completeness – Support wide range of library
6. Free & Open Source – Can be downloaded freely and source code can be modify for
improvement

Shortcomings of Python
1. Lesser libraries – as compared to other programming languages like C++, Java,.net
2. Slow language – as it is interpreted languages, it executes the program slowly.
3. Weak on Type-binding – It not pin point on use of a single variable for different data
type.

How to work in Python


1. Interactive Mode
2. Script Mode

Data Handling
Most of the computer programming language support data type, variables,operator and
expression
like fundamentals. Python also support these.

Data Types: Data Type specifies which type of value a variable can store. The type( )
function is used to determine a variable's type in Python.
e.g.:
>>> x = 2
>>> type(x)
<class ‘int’>

Datatypes in Python
1. Number: It is used to store numeric values Python has three numeric types:
i. Integers: Integers or int are positive or negative numbers with no decimal point.
Integers in Python 3 are of unlimited size.
e.g.:
>>> a = 10
>>> b = 22 * 2
>>> print(a)
10
>>> print(b)
44
Type Conversion of Integer: The int( ) function converts any data type to integer.
e.g.
>>>a = "101" # This is a string. Since it is enclosed with inverted commas.
>>>b = int(a) # It converts string data type to integer.
>>>c = int(122.4) # It converts float data type to integer.
>>>print(b)
101
>>>print(c)
122

ii. Floating point numbers: It is a positive or negative real number with a decimal
point.
e.g.
>>>a = 101.2
>>>b = -101.4
>>>print(a)
101.2
>>>print(b)
-101.4

Type Conversion of Floating point numbers: The float( ) function converts any
data type to floating point number.
e.g.
>>>a = '301.4' #This is a string
>>>print(a)
‘301.4’
>>>b = float(a) #converts string data type to floating point number.
>>>print(b)
301.4

iii. Complex numbers: Complex numbers are combination of a real and imaginary
part. Complex numbers are in the form of X+Yj, where X is a real part and Y is
imaginary part.
e.g.
>>>a = complex(5) # convert 5 to a real part value and zero imaginary part
>>>print(a)
(5+0j)
>>>b=complex(101,23) #convert 101 with real part and 23 as imaginary part
>>>print(b)
(101+23j)

2. String: A string is a sequence of characters. In python we can create string using


single (' ') or double quotes (" ").Both are same in python.
e.g.
>>>str = 'Computer Science'
>>>print('str: ', str)
str: Computer Science

Iterating through string


>>>str = 'comp'
>>>for i in str:
print(i)
c
o
m
p

3. Boolean: It is used to store two possible values either true or false.


e.g.
>>>str = "comp sc"
>>>boo = str.isupper() # test if string contains upper case
>>>print(boo)
False

4. List: Lists are used to store multiple items in a single variable. Lists are created using
square brackets. E.g.:
>>>thislist = ["apple", "banana", "cherry"]

List items are ordered, changeable, and allow duplicate values. List items are
indexed, the first item has index [0], the second item has index [1] and so on.
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change. If you add new items to a list, the new items will be placed
at the end of the list.
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists are indexed, lists can have items with the same value.
e.g.:
>>>lst = [5,99]
>>>print(lst)
[5,99]
>>>lst[0] = 34
>>>print(lst)
[34,99]

5. Tuple: List and tuple, both are same except ,a list is mutable python objects and tuple
is immutable Python objects. Immutable Python objects mean you cannot modify the
contents of a tuple once it is assigned. In order to change the values we have to
redefine the Tple.
e.g.
>>>tup = (66,99)
>>>tup[0] = 3 # error message will be displayed since tuple is unchangable
>>>print(tup[0])
66
>>>print(tup[1])
99

6. Set: It is an unordered collection of unique and immutable (which cannot be


modified)items. A set is a collection which is unordered, unchangeable*, and
unindexed. Set items are unchangeable, but you can remove items and add new items.
Since, Sets are unordered, so you cannot be sure in which order the items will appear.
Sets cannot have two items with the same value.
e.g.
>>>set1 = {11,22,33,22}
>>>print(set1)
{33,11,22}

7. Dictionary: It is an unordered collection of items and each item consist of a key and
a value.
e.g.
>>>dict = {'Subject': 'Comp Sc', 'class': 12}
>>>print(dict)
{'sub': 'Comp Sc', 'class': 12}

Operators
Operators (symbols/keywords) are used to perform arithmetic/logical operations on
variables and values. Python divides the operators in the following groups:
Arithmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Assignment operators: Assignment operators are used to assign values to variables.


Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison operators (Relational): Comparison operators are used to compare two


values.
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical operators: Logical operators are used to combine conditional statements.


Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
Reverse the result, returns False if the result is
not not(x < 5 and x < 10)
true

Identity operators: Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory location.
Operator Description Example
is Returns True if both variables are the same object x is y
Returns True if both variables are not the same
is not x is not y
object

Membership operators: Membership operators are used to test if a sequence is


presented in an object.
Operator Description Example
Returns True if a sequence with the specified
in x in y
value is present in the object
Returns True if a sequence with the specified
not in x not in y
value is not present in the object

Bitwise operators: Bitwise operators are used to compare (binary) numbers.


Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
Shift left by pushing zeros in from the right and
<< Zero fill left shift
let the leftmost bits fall off
Shift right by pushing copies of the leftmost bit
>> Signed right shift
in from the left, and let the rightmost bits fall off
Expression
It is a valid combination of operators, literals and variable.
1. Arithmetic expression :- e.g. c = a + b
2. Relational expression :- e.g. x>y
3. Logical expression :- a or b
4. String expression :- c = “comp” + “sc”

Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion: Implicit Type
Conversion & Explicit Type Conversion.

Implicit Type Conversion: In Implicit type conversion, Python automatically


converts one data type to another data type. This process doesn't need any user
involvement. e.g.
num_int = 12
num_flo = 10.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

OUTPUT
('datatype of num_int:', <type 'int'>)
('datatype of num_flo:', <type 'float'>)
('Value of num_new:', 22.23)
('datatype of num_new:', <type 'float'>)

Explicit Type Conversion: In Explicit Type Conversion, users convert the data type
of an object to required data type. We use the predefined functions like
int(),float(),str() etc. e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
Python math Module
Python has a built-in module that you can use for mathematical tasks.
Math Methods
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
Returns the number of ways to choose k items from n items without
math.comb()
repetition and order
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
Returns the Euclidean distance between two points (p and q), where p
math.dist()
and q are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
Returns the inverse of math.frexp() which is x * (2**i) of the given
math.ldexp()
numbers x and i
math.lgamma() Returns the log gamma value of x
Returns the natural logarithm of a number, or the logarithm of number to
math.log()
base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
Returns the number of ways to choose k items from n items with order
math.perm()
and without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
Returns the closest value that can make numerator completely divisible
math.remainder()
by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number

Control Statements
Control statements are used to control the flow of execution depending upon the specified
condition/logic. There are three types of control statements: Decision Making Statements,
Iteration Statements (Loops) & Jump Statements (break, continue, pass).
i. Decision making statements: used to control the flow of execution of a program
depending upon condition. There are three types of decision making statements.
a) if statements: An if statement is a programming conditional statement that, if
proved true, performs a function or displays information.
Syntax:
if(condition):
[statements]
b) if-else statements: This statement executes some code if the test expression is
true (nonzero) and some other code if the test expression is false.
Syntax:
if(condition):
statements
else:
statements
c) Nested if-else statement: The nested if...else statement allows you to check for
multiple test expressions and execute different codes for more than two
conditions.
Syntax
if (condition):
statements
elif (condition):
statements
else:
statements
ii. Iteration statements(loop): used to execute a block of statements as long as the
condition is true. Loops statements are used when we need to run the same code again
and again. Python Iteration (Loops) statements are of three type :-
a) While Loop: It is used to execute a block of statement as long as a given
condition is true. And when the condition becomes false, the control will come
out of the loop. The condition is checked every time at the beginning of the loop.
Syntax:
while (condition):
statement/[statements]
b) For Loop: It is used to iterate over items of any sequence, such as a list or a
string.
Syntax:
for val in sequence:
statements
iii. Jump Statements (break, continue, pass): Jump statements are used to transfer the
program's control from one location to another. Means these are used to alter the flow
of a loop like – to skip a part of a loop or terminate a loop There are three types of
python.
a) break
b) continue
c) pass

Function
A function is a programming block of codes which is used to perform a single, related task.
It only runs when it is called. We can pass data, known as parameters, into a function. A
function can return data as a result.

We have already used some python built-in functions like print(),etc. But we can also create
our own functions. These functions are called user-defined functions.

Advantages of Using functions:


1. Program development made easy and fast : Work can be divided among project
members thus implementation can be completed fast.
2. Program testing becomes easy : Easy to locate and isolate a faulty function for further
investigation
3. Code sharing becomes possible : A function may be used later by many other
programs; this means that a python programmer can use a function to write others,
instead of starting over from scratch.
4. Code re-usability increases : A function can be used to keep away from rewriting the
same block of codes which we are going to use in two or more local programs. This
is especially useful if the code involved is long or complicated.
5. Increases program readability :It makes possible top down modular programming.In
this style of programming, the high level logic of the overall problem is solved first
while the details of each lower level function are addressed later.The length of the
source program can be reduced by using functions at appropriate places.
6. Function facilitates procedural abstraction : Once a function is written it serves as a
black box. All that a programmer would have to know to invoke function would be
to know its name, and the parameters that it expects
7. Functions facilitate the factoring of code : A function can be called in other functions
and so on.

Creating and calling a Function


A function is defined using the def keyword in python. E.g. program is given below:

def my_function(x,y): # Function definition, my_function is the name of function


z=x+y # x, y are called as formal parameters.
return z # the return keyword returns a value from the function.

a = 12
b = 10
print(my_function(a,b)) # a, b are called actual parameters. Holds the actual value
that is sent to my_function and processed.
OTPUT: Using a function is called Function call/invoke
22
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among the whole program using global
keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal keywords.

Local variable program:


def fun():
s = "I love India!" #local variable
print(s)

s = "I love World!"


fun()
print(s)

Output:
I love India!
I love World!

Global variable program:


def fun():
global s #accessing/making global variable for fun()
print(s)
s = "I love India!“ #changing global variable’s value
print(s)

s = "I love world!"


fun()
print(s)

Output:
I love world!
I love India!
I love India!

Non local variable


def fun1():
x = 100
def fun2():
nonlocal x #change it to global or remove this declaration
x = 200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))

x=50
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50

Function Parameters / Arguments


These are specified after the function name, inside the parentheses. Multiple parameters are
separated by comma. The following example has a function with two parameters x and y.
When the function is called, we pass two values, which is used inside the function to sum up
the values and store in z and then return the result(z):
def sum(x,y): #x, y are formal arguments
z=x+y
return z #return the result

x,y = 4,5
r = sum(x,y) #x, y are actual arguments
print(r)

Note :-
1. Function Prototype is a declaration of function with name ,argument and return type.
2. A formal parameter, i.e. a parameter, is in the function definition. An actual
parameter, i.e. an argument, is in a function call.

Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments - arguments passed to a function in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to arguments.
• Variable-length arguments – pass multiple values with a single argument name.

#Required arguments
def square(x):
z=x*x
return z
r=square()
print(r)
#In above function square() we have to definitely need to pass some value to argument x.

#Keyword arguments
def fun( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


fun( age=15, name="mohak" )

# value 15 and mohak is being passed to relevant arguments based on keywords used for
them.
#Default arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum()
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
#default value of x and y is being used when it is not passed

#Variable length arguments


def sum( *vartuple ):
s=0
for var in vartuple:
s=s+int(var)
return s;

r=sum( 70, 60, 50 )


print(r)
r=sum(4,5)
print(r)
#now the above function sum() can sum n number of values

#Pass by reference
def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))

OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed and its contents are changing because it is
mutable that’s why it is behaving like pass by reference

#Pass by value
def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b=5
print(id(b))
updateNumber(b)
print(b)
print(id(b))

OUTPUT
1691040064
1691040064
1691040224
5
1691040064
#In above function value of variable b is not being changed because it is immutable that’s
why it is behaving like pass by value.
UNIT – I
Section B
Computational Thinking & Programming – 2

File Handling
A file is a sequence of bytes on the disk/permanent storage where a group of related data is
stored. File is created for permanent storage of data.
In programming, Sometimes, it is not enough to only display the data on the console. Those
data are to be retrieved later on, then the concept of file handling comes. It is impossible to
recover the programmatically generated data again and again. However, if we need to do so,
we may store it onto the file system which is not volatile and can be accessed every time.
Here, comes the need of file handling in Python.
File handling in Python enables us to create, update, read, and delete the files stored on the
file system through our python program. The following operations can be performed on a
file. In Python, File Handling consists of following three steps:
 Open the file
 Process file
 Close the file

Types of File
There are two types of files:
 Text Files- A file whose contents can be viewed using a text editor is called a text
file. A text file is simply a sequence of ASCII or Unicode characters. Python
programs, contents written in text editors are some of the example of text files.
 Binary Files- A binary file stores the data in the same way as stored in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of
binary files. We can’t read a binary file using a text editor.

Text File Binary File


Its Bits represent character. Its Bits represent a custom data.
Less prone to get corrupt as change reflects Can easily get corrupted, corrupt on even
as soon as made and can be undone. single bit change.
Store only plain text in a file. Can store different types of data (audio,
text, and image) in a single file.
Widely used file format and can be opened Developed for an application and can be
in any text editor. opened in that application only.
Mostly .txt and .rtf are used as extensions Can have any application defined
to text files. extension.

File Opening Modes


Sr. No. Mode Description
Reading only. Sets file pointer at beginning of the file. This is the
1 r
default mode.
2 rb Same as r mode but with binary file.
Both reading and writing. The file pointer placed at the beginning
3 r+
of the file.
4 rb+ Same as r+ mode but with binary file.
Writing only. Overwrites the file if the file exists. If not, creates a
5 w
new file for writing.
6 wb Same as w mode but with binary file.
Both writing and reading. Overwrites . If no file exist, creates a
7 w+
new file for R & W.
8 wb+ Same as w+ mode but with binary file.
For appending. Move file pointer at end of the file. Creates new
9 a
file for writing, if not exist.
10 ab Same as a but with binary file.
For both appending and reading. Move file pointer at end. If the
11 a+
file does not exist, it creates a new file for reading and writing.
12 ab+ Same as a+ mode but with binary mode.

FILE HANDLING METHODS


The open( ) method
Before any reading or writing operation of any file, it must be opened first of all. The
function open( ) is used to open a file. On calling of this function, it creates a file object for
file operations.
Syntax:
file_object = open(<file_name>, <access_mode>)

file_name = name of the file, enclosed in double quotes.


access_mode = Determines what kind of operations can be performed with the file, like read,
write etc.

E.g. :
f = open(“MyFile.txt”, “w”)

The close( ) Method


Used to close an open file. After using this method, an opened file will be closed and a closed
file cannot be read or written any more.
Syntax: file_object.close( )
E.g.:
f = open("a.txt", 'a+')
print(f.closed)
print("Name of the file is",f.name)
f.close()
print(f.closed)

OUTPUT
False
Name of the file is a.txt
True

The write( ) Method


It writes the contents to the file in the form of string. It does not return value. Due to
buffering, the string may not actually show up in the file until the flush() or close() method
is called.

The read( ) Method


It reads the entire file and returns it contents in the form of a string. Reads at most size bytes
or less if end of file occurs. If size not mentioned then read the entire file contents.
E.g.:
f = open("a.txt", 'w')
line1 = 'Welcome to LFS'
f.write(line1)
line2="\nRegularly visit LFS"
f.write(line2)
f.close()
f = open("a.txt", 'r')
text = f.read()
print(text)
f.close()

OUTPUT
Welcome to LFS
Regularly visit LFS

Another way to read a file is to call a certain number of characters like in the following
code the interpreter will read the first five characters of stored data and return it as a
string:
# Python code to illustrate read() mode character wise
file = open("myFile.txt", "r")
print (file.read(5))

The readline([size]) method


Read no. of characters from file if size is mentioned till EOF. Read line till new line
character. Returns empty string on EOF.
E.g.:
f = open("a.txt", 'w')
line1 = 'Welcome to LFS’
f.write(line1)
line2="\nRegularly visit LFS"
f.write(line2)
f.close()
f = open("a.txt", 'r')
text = f.readline()
print(text)
text = f.readline()
print(text)
f.close()

OUTPUT
Welcome to LFS
Regularly visit LFS

The readlines([size]) method


Read no. of lines from file if size is mentioned or all contents if size is not mentioned.
E.g.:
f = open("a.txt", 'w')
line1 = 'Welcome to LFS'
f.write(line1)
line2="\nRegularly visit LFS"
f.write(line2)
f.close()
f = open("a.txt", 'r')
text = f.readlines(1)
print(text)
f.close()
OUTPUT
'Welcome to LFS'

The with( ) Method


We can also use the write function along with the with( ) function:
# Python code to illustrate with( ) alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")

The split( ) Method


We can also split lines using file handling in Python. This splits the variable when space
is encountered. You can also split using any characters as we wish. Here is the code:
# Python code to illustrate split() function
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Example Code: Processing Every Word in a File


f = open("a.txt", 'w')
line1 = 'Welcome to LFS'
f.write(line1)
line2="\nRegularly visit LFS"
f.write(line2)
f.close()
f = open("a.txt", 'r')
for text in f.readlines():
for word in text.split( ):
print(word)
f.close()

OUTPUT
Welcome
to
LFS
Regularly
visit
LFS

The writable( ) Method


The Python file writable() method is an inbuilt method that returns True if the file is writable
otherwise it will return False if the file is not writable. A file is writable only if it’s opened
using “w” for write and “a” for append.
Example:
myfile = open("examplefile.txt", "w")
print(myfile.writable())
myfile.close()

The readable( ) method


The readable( ) method in Python is an inbuilt method in python, it checks whether a file is
readable or not. This method returns a boolean value. The readable() method returns True if
the file is readable otherwise it will return False.
Example:
myfile = open("examplefile.txt", "r")
print(myfile.readable())
myfile.close()

The flush( ) method


The flush( ) method is an inbuilt method in python. It is used to clear the internal buffer
when writing to file. It is the best method while working with file handling in python.
Example:
myfile = open("examplefile.txt", "a")
myfile.write("Welcome to python")
myfile.flush()
myfile.write("Programming.....")

ABSOLUTE PATH VS. RELATIVE PATH


An absolute path is a path that describes the location of a file or folder regardless of the
current working directory; in fact, it is relative to the root directory.
A relative path that depicts the location of a file or folder is relative to the current working
directory. Unlike absolute paths, relative paths contain information that is only relative to
the current document within the same website, which avoids the need to provide a full
absolute path.
Absolute file paths start with a leading forward slash and describe how to access a given file
or directory, starting from the root of the file system. Relative file paths do not start with a
leading forward slash and are interpreted from the perspective of the current working
directory.
import os

os.mkdir("myFolder") #--> Create a directory


path = 'myFolder/test.txt' #--> Assign absolute path
f = open(path,'w') #--> Open file
print(os.path.abspath(path)) #--> Display path
print(os.getcwd()) #--> Display current working directory
f.close() #--> Close the file

The OS module in Python provides functions for creating and removing a directory
(folder), fetching its contents, changing and identifying the current directory, etc.

To Change working Directory


>>> import os
>>> os.chdir("C:\MyPythonProject") # changing current working directory
>>> os.getcwd()
'C:\MyPythonProject'

The tell( ) Method


The tell() method returns the current file position in a file stream.
Syntax: file.tell()
It has no parameter values.
Example:
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())
f.close()

The seek( ) method


In Python, seek( ) function is used to change the position of the File Handle to a given
specific position. File handle is like a cursor, which defines from where the data has to be
read or written in the file.

Syntax: f.seek(offset, from_what), where f is file pointer

Parameters:-
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.

# Python program to demonstrate


# seek() method

# Opening "GfG.txt" text file


f = open("GfG.txt", "r")

# Second parameter is by default 0, sets Reference point to twentieth, index position from
the beginning
f.seek(20)

# prints current position


print(f.tell())

print(f.readline())
f.close()

You might also like