Sunday, May 17, 2026

Python Material - Part - 16 - Files

__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------

===================================================================================
                                PART -1

==================================================================================

"""

File handling is an important part of any web/mobile/desktop/hardware application
Python has several functions for creating, reading, updating, and deleting files.

Most useful files in real-time
Notepad file (.txt), Json file (.json), (.yaml), Excel file(.xls)

The key function for working with files in Python is the open() function.

The open() function takes two arguments: filename, mode.

## Syntax for Open a file
f_object = open(filename_along_with_path, [mode])

There are different modes for opening a file:
txt file modes: r r+ w w+ a a+ ---> 6
binary file modes: rb rb+ wb wb+ ab ab+ --->6

f_o = open("Raahi.txt", "r+")
modes
1.r
Opens a file for reading only.
The file pointer is placed at the beginning of the file.
Note: This is the default mode.

2.rb
Opens a file for reading only in binary format.
The file pointer is placed at the beginning of the file.
This is the default mode for binary files.

3. r+
Opens a file for both reading and writing.
The file pointer placed at the beginning of the file.

4. rb+

Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning of the binary file.

5. w

Opens a file for writing only.
If the file does not exist, creates a new file for writing.
Overwrites the file if the file exists.

6. wb

Opens a file for writing only in binary format.
If the file does not exist,creates a new file for writing.
Overwrites the file if the file exists.

7. w+
Opens a file for both writing and reading.
If the file does not exist,creates a new file for reading and writing.
Overwrites the existing file if the file exists.


8. wb+
Opens a file for both writing and reading in binary format.
If the file does not exist,creates a new binary file for reading and writing.
Overwrites the existing file if the file exists.

9. a
f_p = open("log.txt", 'a')
Opens a file for appending only (writing only).
The file pointer is at the end of the file if the file exists.
If the file does not exist,it creates a new file for writing only.

10. ab

Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists.
If the file does not exist, it creates a new file for writing.

11. a+

Opens a file for both appending and reading.
The file pointer is at the end of the file if the file exists.
If the file does not exist, it creates a new file for reading and appending.

12. ab+
Opens a file for both appending and reading in binary format.
The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

"""
x = "kruthika"
"""
1. fileobject.closed --> Returns True if file is closed, False otherwise.
2. fileobject.mode ---> Returns access mode with which file was opened.
3. fileobject.name ---> Returns name of the file.
"""


# f_obj = open("raahi.txt", "w+") # Opening a file for writing and reading
# print("Name of the file: ", f_obj.name) # not required mostly
# print("Closed or not : ", f_obj.closed)
# print("which mode : ", f_obj.mode) # not required mostly
# f_obj.close() # file closed here
# print("Closed or not : ", f_obj.closed)


"""
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file.

Syntax : fileObject.close()
"""


"""
The write() Method
The write() method writes any string to an open file.
It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string

Syntax : fileObject.write(string)
"""


# f_obj = open("Venkat.txt", "w+") # Opening a file for reading and writing
# f_obj.write("This is my python file \t Yeah its great!!\nWriting in next line")
# f_obj.write("\nI hope you understand")
# f_obj.close() # Closed the open file
# print("Closed or not : ", f_obj.closed)


"""
The read() Method
The read() method reads a string from an open file.
It is important to note that Python strings can have binary data. apart from text data.

Syntax: fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and
if count is missing, then it tries to read as much as possible, maybe until the end of file.
"""
#
# f_obj = open("Venkat.txt", "r+") # Opening a file for reading & writing
# data_from_txt_file = f_obj.read() # this line can read complete content of the file
# print(data_from_txt_file)
# f_obj.close() # Closing the opened file


# f_obj = open("Venkat.txt", "r+") # Opening a file for reading & writing
# data_from_txt_file = f_obj.read(10) # this line can read only 10 characters from the file given by user
# print(data_from_txt_file)
# f_obj.close() # Closing the opened file
"""
OUTPUT:
This produces the following result

Read String is : Python is

"""


"""
File Positions
The tell() method tells you the current cursor position within the file;
in other words, the next read or write will occur at that many bytes from the beginning of the file.

The seek() method changes the current cursor position.
syntax: seek(offset, [from])
offset --> The offset argument indicates the number of bytes to be moved.
from --> The from argument specifies the reference position from where the bytes are to be moved.

If from is set to 0, the beginning of the file is used as the reference position.
If it is set to 1, the current position is used as the reference position.
If it is set to 2 then the end of the file would be taken as the reference position.
"""
# print(r"swetha\narendra") # raw_ string concept
#
# f_obj = open("Manikanta.txt", "w+") # Open a file
# f_obj.write("qwerty This is my python file \t Yeah its great!!\nWriting in next line")
# f_obj.write("\nI hope you understand")
# position = f_obj.tell() # current position of the cursor
# print("Current cursor position in file: ", position)
# f_obj.seek(7, 0)
# print("Current cursor position in file: ",f_obj.tell())
# str = f_obj.read()
# print(str)
# position = f_obj.tell() # current position of the cursor
# print("Current cursor position in file: ", position)
# print("mode is: ", f_obj.mode)
# f_obj.seek(0, 0) # file pointer will move to the starting of the file
# f_obj.write("Ganesh")
# f_obj.close()
# print(f_obj.closed)

"""
This produces the following result
Read String is : This isBha
Current cursor position in file: 10
mode is: r+
Again read String is : file Yeah its great!!
I hope you understand
Writing in next line
True

"""

# x = open("ganesh.txt","w+")
# x.write("Hi,\nThis is Kruthika and my qualification is B.tech")
# x.seek(10,0)
# print(x.read())
# x.close()

# data = [3, 5, 6, 7, 8]
# output = data[2]
# print(output)
#
# print([3, 5, 6, 7, 8][2])
"""
readlines([index]) is a files inbuilt-function.
readlines() function will read the content in the form of lines and it will store each line in a list
"""


def read_line_wise(file_name_along_with_path):
f_obj = open(file_name_along_with_path) # if you are not providing mode by default it consider as read mode
output = f_obj.readlines() # it will store the data in a list
# print(output)
print(output[2]) # we will access the required line based on index
f_obj.close()

# file_name_along_with_path = "Manikanta.txt"
# read_line_wise(file_name_along_with_path)



def read_line_wise(file_name_along_with_path):
f_obj = open(file_name_along_with_path,"w+")
f_obj.write("qwerty This is my python file \t Yeah its great!!\nWriting in next line")
f_obj.write("\nI hope you understand")
f_obj.seek(0,0)
output = f_obj.readlines() # it will store the data in a list
# print(output)
print(output[1]) # we will access the required line based on index
f_obj.close()


# file_name_along_with_path = r"C:\Users\nanarend\Downloads\Narendra_shell_scripts\nanditha.txt"

# read_line_wise(file_name_along_with_path)

def read_line_wise(file_name_along_with_path):
with open(file_name_along_with_path,"w+") as f_obj:
f_obj.write("qwerty This is my python file \t Yeah its great!!\nWriting in next line")
f_obj.write("\nI hope you understand")
f_obj.seek(0,0)
output = f_obj.readlines() # it will store the data in a list
# print(output)
print(output[1]) # we will access the required line based on index



"""
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.

To use this module, you need to import it first and then you can call any related functions.

The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
"""

import os


# # Rename a file from test1.txt to test2.txt
# os.rename("Indhu.txt", "Suresh.txt" )
#
# os.remove("Suresh.txt")
#

"""
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.

Syntax

import os
os.remove("Narendra.txt")

"""


"""
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and change directories.

The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.

Syntax
# os.mkdir("folder name")

# """
import os

# Create a directory
# os.mkdir("Narendra") # Uses current location as default path
# os.mkdir(R"E:\Narendra_Training_Data\Manual Training Data\General Testing content\teja") # where ever you want to create a folder you can provide the path
# x = open(r"E:\Narendra_Training_Data\Manual Training Data\General Testing content\Srikanth.txt", "a+")

# """
# The chdir() Method
# You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.
#
# Syntax
# os.chdir("Files")
# """


# # # Changing a directory to "/home/newdir"
# os.chdir(r"C:\Users\MY PC\Desktop\python cuts\My Practice")
#
# """
# The getcwd() Method
# The getcwd() method displays the current working directory.
#
# Syntax
# print(os.getcwd())
"""
#
#
# import os
# # # #
# # # # # This would give location of the current directory

"""
# x = os.getcwd()
# print(x)
# The rmdir() Method
# The rmdir() method deletes the directory, which is passed as an argument in the method.
#
# Before removing a directory, all the contents in it should be removed.
#
# Syntax
# os.rmdir('Narendra')
# f_obj = open("indhu.txt","w+")
# f_obj.write("Hi this is manjula")
# f_obj.close()

# with open("suresh.txt",'w+') as f_obj:
# f_obj.write("my first file\n")
# f_obj.seek(0,0)
# print(f_obj.read())

# x = "abcdefwer"
# for i in range(len(x)):
# print(i)

#
# x = "abcdef"
# iterator = "a"
# #
# while iterator in x:
# print(x)
# x = x[:-1] # "aabcdefw"
# print(iterator, x)

===================================================================================
                                Practice file
===================================================================================
__author__ = "Narendra Boyina"
"""
reading and writing
1. open() mostly take 2 arguments
1. file: path to file(required)
2. mode: read/write/append, binary/text this is optional
explicit is better than implicit
3. encoding: text encoding
python differentiate b/w files opened in text mode /binary mode.

2. By default, Every systems have default encoding mechanisms.

Python 2.7.x
import sys
sys.getdefaultencoding()
'ascii'
or

Python 3.5.2
import sys
sys.getdefaultencoding()
'utf-8'
3. f = open('a.txt', mode='wt', 'encoding'='utf-8')
w means write, t means text

'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
"""
import os
f = open("D:\Python\python practice\Filetest.txt","wt")
f.write("This is the 1st program practicing in python files."
" \nEvery time after writing some data in the file, we must close the file properly by using f.close()).\nAfter reading the file we must close the file")
f.close()
f = open("D:\Python\python practice\Filetest.txt","r")
print(f.read())
f.close()


"""# for writing data into a file
import os

##a=open('c:/txt/s.txt',"w")
##a.write("hi ravi how are you ?")
##a.close()
##a=open('c:/txt/s.txt','r')
##print(a.read())
##a.close()
##os.rename('c:/txt/s.txt','c:/txt/zzz.txt') #(for this you need to import os module)
# Every time new file name need to be change before executing file otherwise WindowsError: [Error 183] Cannot create a file when that file already exists
##os.remove('c:/txt/aaaaaa.txt') #Removing a File (for this you need to import os module)
"""
import os
f = open("D:\Python\python practice\Filetest.txt","wt")
f.write("This is the 1st program practicing in python files."
"\nEvery time after writing some data in the file, we must close the file properly by using f.close().\nAfter reading the file we must close the file")
f.close()
f = open("D:\Python\python practice\Filetest.txt","r")
print(f.read())
f.close()

Author: Boyina Narendra

Supporting Author: M. Meera Sindhu

Request: If you find this information useful, please provide your valuable comments

No comments:

Post a Comment