Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Strings

The document provides an overview of file handling in Python, detailing the types of files (text and binary) and their characteristics. It explains the various access modes for opening files, the syntax for file operations, and methods for writing to files. Additionally, it covers built-in string manipulation methods in Python, illustrating their usage with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Strings

The document provides an overview of file handling in Python, detailing the types of files (text and binary) and their characteristics. It explains the various access modes for opening files, the syntax for file operations, and methods for writing to files. Additionally, it covers built-in string manipulation methods in Python, illustrating their usage with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Python File Handling

Samir V
Two types of files can be handled in Python, normal text files and binary files
(written in binary language, 0s, and 1s).

Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in
Python by default.
A regular text file can be understood as a sequence of characters consisting of
alphabets, numbers and other special symbols. These files are with extensions
like .txt, .py etc
Few text file contents are usually separated comma (,) or tab (\t).Thse files are
called csv (comma separated value) or tsv(tabs seperated value) respectively

Binary files: In this type of file, there is no terminator for a line, and the data is
stored after converting it into machine-understandable binary language.
Binary files are stored in a computer in a sequence of bytes. Even a single bit
change can corrupt the file and make it unreadable to the supporting
application.
Binary files operations are faster than text file as it is deliminator free hence
translation is not required.
slide 2
Samir V
In Python, there are six methods or access modes, which are:

Read Only ('r’): This mode opens the text files for reading only. It raises the I/O
error if the file does not exist. This is the default mode for opening files as well.

Read and Write ('r+’): This method opens the file for both reading and writing. If
the file does not exist, an I/O error gets raised.

Write Only ('w’): This mode opens the file for writing only. The data in existing files
are overwritten. If the file does not already exist in the folder, a new one gets
created.

Write and Read ('w+’): This mode opens the file for both reading and writing. The
text is overwritten and deleted from an existing file.

Append Only ('a’): This mode allows the file to be opened for writing. If the file
doesn't yet exist, a new one gets created. The newly written data will be added at
the end, following the previously written data.

Append and Read (‘a+’): Using this method, you can read and write in the file. If the
file doesn't already exist, one gets created. The newly written text will be added at
the
slide 3 end.
Samir V
Opening a file

To open a file in Python, we use the open() function. The syntax of open() is
as follows:
file_object= open(file_name, access_mode)

This function returns a file object called file handle which is stored in the
variable file_object. This file handle is used to transfer data to and from the
file (read and write).
If the file does not exist, the above statement creates a new empty file and
assigns it the name we specify in the statement.

The file handle has certain attributes that tells us basic information about
the file, such as: file location, mode, capacity, metadata etc.

# to open the file "MyFile1.txt”presentin current directory


file1 = open("MyFile1.txt","a")

# To open a file at specific location


file2 = open("D:\\Text\\MyFile2.txt","w+")

slide 4
Samir V
Notice the doble slashes in file path "D:\\Text\\MyFile2.txt“
This is to avoid escape sequences. For eg. \t inserts tab space.

If you do not want to add double slashes, python provide alternate way-

file2 = open(r "D:\Text\MyFile2.txt","w+")

One need to r preceding the file path. This tells interpreter to treat the path
as raw string.

slide 5
Samir V
Closing a file

Once we are done with the read/write operations on a file, it is a good


practice to close the file. Python provides a close() method to do so.
While closing a file, the system frees the memory allocated to it. The
syntax of close() is:
file_object.close()

Here, file_object is the object that was returned while opening the file.
Python makes sure that any unwritten or unsaved data is flushed off
(written) to the file before it is closed. Hence, it is always advised to
close the file once our work is done.

# Opening and Closing a file "MyFile.txt"

file1 = open("MyFile.txt","a")
….
….
file1.close()

slide 6
Samir V
WRITING TO A TEXT FILE

For writing to a file, we first need to open it in write or append mode. If we open
an existing file in write mode, the previous data will be erased, and the file
object will be positioned at the beginning of the file.

On the other hand, in append mode, new data will be added at the end of the
previous data as the file object is at the end of the file.

After opening the file, we can use the following methods to write data in the file.
• write() - for writing a single string
File_object.write(str1)

text = "This is new content"


# writing new content to the file
fp = open("write_demo.txt", 'w')
fp.write(text)
fp.close()

If numeric data are to be written to a text file, the


data need to be converted into string before writing to
slide 7
Samir V
If numeric data are to be written to a text file, the data need to be converted
into string before writing to the file.

myobject=open("myfile.txt",'w’)
marks=58
#number 58 is converted to a string using str()
myobject.write(str(marks))

slide 8
Samir V
• writelines() - for writing a sequence of strings
Syntax - File_object.writelines(L) for L = [str1, str2, str3]

file1 = open("Employees.txt", "w")


lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Data is written into the file.")

slide 9
Samir V
Python includes the following some built-in methods to manipulate strings −

1) capitalize() :- Python String capitalize() method returns a copy of the string


with only its first character capitalized.

e.g.: str = "this is string example....wow!!!";


print str.capitalize()
>> This is string example....wow!!!

2) center() :- Python string method center() returns centered in a string of


length width. Padding is done using the specified fillchar. Default filler is a
space.
Syntax: str.center(width [, fillchar])

e.g.: str = "this is string example....wow!!!"


print str.center(40,'@’)
>> @@@@this is string example....wow!!!@@@@

Samir V
3) count():- Python string method count() returns the number of occurrences
of substring sub in the range [start, end].

Syntax: str.count(sub, start, end)


Parameters: sub − This is the substring to be searched.
start − Search starts from this index. By default search starts from 0 index.
end − Search ends from this index. By default search ends at the last index.

e.g.: str = "this is string example....wow!!!“


sub = "i"
print (str.count(sub, 4, 40))
>> 2

sub = "wow"
print (str.count(sub))
>> 1

Samir V
4) find():-
Python string method find() determines index, if string str occurs in string, or
in a substring of string if starting index beg and ending index end are given.

Syntax: str.find(str, beg, end) This method return index number if str found
otherwise -1.
e.g.:
str1 = "this is string example....wow!!!”
str2 = "exam"

print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)

rfind() method finds the last occurrence of the specified value.


Syntax - string.rfind(value, start, end)

txt = "Hello, welcome to my world."


x = txt.rfind("e", 5, 10)
print(x)

>> 8 Samir V
5) index():- Python index() determines index, if string str occurs in string, or
in a substring of string if starting index beg and ending index end are given.
This method is same as find(), but raises an exception if sub is not found.

Syntax: str.index(str, beg, end)

e.g.: str1 = "this is string example....wow!!!


“ str2 = "exam"
print str1.index(str2)
print str1.index(str2, 10)
print str1.index(str2, 40)

6) islower():- This method checks whether all characters (letters) of the string
are lowercase. If yes it will return TRUE else FALSE

Syntax: str.islower()

7) isupper():- This method checks whether all characters (letters) of the


string are Uppercase. If yes it will return TRUE else FALSE

Syntax: str.isupper() Samir V


8) join() :- This method joins elements in a sequence into a single string. It
takes a sequence (such as a list, tuple, or string) as its parameter and returns
a new string where the elements of the sequence are concatenated using a
specified string as a separator.

Eg -
my_string = "hello"
str1 = '-'

result = str1.join(my_string)
print(result)

>> h-e-l-l-o

list_1 = ['Hello', 'world', '!', 'This', 'is', 'Python']


str2 = ' '

result = str2.join(list_1)
print(result)

>> Hello, world! This is Python


Samir V
9) len():- Python string method len() returns the length of the string.
Syntax: len(str)

e.g.:
str = "this is string example....wow!!!"
print "Length of the string: ", len(str)
O/P: Length of the string: 32

10) lower():- Python string method lower() returns a copy of the string in
which all case-based characters have been lowercased.
Syntax: str.lower()

e.g.: str = "THIS IS STRING EXAMPLE....WOW!!!" print str.lower()


>> this is string example....wow!!!

11) upper():- Python string method upper() returns a copy of the string in
which all case-based characters have been uppercased.
Syntax: str.upper()

e.g.: str = " this is string example....wow!!!” print str.upper()


>> THIS IS STRING EXAMPLE....WOW!!!
Samir V
11) replace():- This method replaces all occurrences of old string by new
string.
Syntax: s.replace(old, new)

s = ‘child is the father’


S= s.replace(‘the’, ‘a’)
print(S)
>> ‘child is a faar’

Following methods return True if condition is satisfied else returns False.

s = ‘Waiting for the break of day’


t = ’25 or 6 to 4’
u = ‘314159’

12) s.isalnum() returns True


13) s.isalpha() returns True
14) t.isalnum() returns True
15) t.isalpha() returns False
16) t.isdigit() returns False
17) u.isdigit() returns True
Samir V

You might also like