Python File Handling

The python open () function is used to open () internally stored files. It returns the contents of the file as python objects.

Consequently, a file operation in Python happens in the following order:

  1. Launch or open a file
  2. Write or read (perform operation)
  3. Save and close the file

Python File Handling

Opening Files in Python

A file can be opened in Python using the built-in open () function. This function returns a handle, often known as a file object, which can be used to read or edit the file appropriately.

Syntax: open (file_name, mode)

Parameters:

file_name: This parameter as the name suggests, is the name of the file that we want to open.

mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:

“r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists.

“w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you.

“a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you.

“x”: This string is used to create a specific file.

“b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files.

“t”: This string is used to handle files in text mode. By default, the open () function uses the text mode.

Example 1: (To get the path we can ask from user using input function)

filename = “names.txt”

filepath = “C:\\Users\\HP\\Desktop\\Python\\”

file = filepath+filename

f = open(file, “r”)

print(f.read())

Example 2: (directly accessing the link, if we don’t provide any mode by default, it is read mode only)

f = open(“C:\\Users\\HP\\Desktop\\names.txt, “r”)

print(f.read())

Example 3:

f = open(“file-name.txt”)      This is equivalent to ‘r’ or ‘rt’

f = open(“file-name.txt”,’w’)   Here the “w” represents for write in text mode

f = open(“file-name.bmp”,’r+b’) # read and write in binary mode

One more option is to read in the size number of data using read(size) method. If this size parameter is not defined, complete file will read till end.

Example 4:

f = open(“C:\\Users\\HP\\Desktop\\names.txt, “r”)

print(f.read(4)) # read the next 4 lines

If there are multiple lines and we need to start from specific line only there we can change our current file cursor (position) using the seek() method. Also, tell() method is useful to returns our current position (in number of bytes).

f.tell()    # get the current file position

f.seek(0)   # bring file cursor to initial position

Python File Handling

Python File Closure

The file must be properly closed after all operations have been completed on it.

The resources that were bound to a file will become available after it has been closed. The Python close () function is used to complete the task.

Python has an unreferenced object garbage collector, but we shouldn’t rely on it to close the file as it may encounter the errors or exceptions also.

Example:

f = open (“C:\\Users\\HP\\Desktop\\names.txt, “r”)

! perform operations as per the requirements

f.close()

Files in write or append mode

Open the file in write w, append a, or exclusive creation x mode before writing to it in Python.

We must exercise caution when using the w mode because it will overwrite any existing data in the file. As a result, all previous data are deleted. whereas a mode will use for append.

The write () method is used to write a string or a sequence of bytes (for binary files). The number of characters written to the file are returned by this procedure.

Example:

with open(“new-file.txt”,’w’,encoding = ‘utf-8’) as f:

f.write(“this is first line\n”)

f.write(“This is second line\n”)

f.write(“This is third line\n”)

If new-file.txt named file doesn’t already exist in the current directory, this script will create it there. If it does, it has been replaced. To distinguish the several lines adding newline characters ourself.

Python File Methods

Split a string into a list where each line is a list item. The splitlines() method splits a string into a list. The splitting is done at line breaks.

command = input.read().splitlines() #Here we are converting all commands in the form of lists; it can be used in netmiko library by this way.

Python File Handling

WITH OPEN?

You gain better syntax and exception handling with the “With” statement.

The common preparation and clean-up tasks are encapsulated in the with statement, which makes exception handling simpler. Additionally, the file will be automatically closed. The use of a clean-up is always guaranteed by the with statement.

file = open(“netminion.txt”)

data = file.read()

print data

file.close()  # here important point is to close the file after using it.

With Statement Usage

Opening a file using with is as simple as: with open(filename) as file:

with open(netminion.txt’, ‘w’) as file:

file.write(‘Hi there!’)

Notice, need not to close this here using “file.close()”. it will automatically close.

Example –

with open(‘commands_file.txt’) as config:

configuration = config.read().splitlines()

#print (configuration)

———————————————————————–

We also offer a diverse library of pre-recorded videos for any online training or buy self-paced courses.
Get enrolled now”.

📩 Email:info@netminion.net, netminionsolutions@gmail.com
📞 Helpline: +91-9599857762(IN), + 19024124779 (CA)
🟣 LinkedInhttps://www.linkedin.com/in/netminion-solutions/
🟢 Websitehttps://netminion.net
🟣 Videos Websitehttps://videos.netminion.in
🟢Telegram Channelhttps://t.me/NetMinionSolitionsOffical
🟣 Buy a Rack Rental : https://labs.netminion.net/page/login/index.php

Keep Learning! Keep Growing! Keep investing!

Welcome to NetMinion Solutions, a leading education training institute/company to nurture minds and fostering a passion for learning. No matter if you are a beginner or a professional – our dedicated faculty and state-of-the-art facilities create an enriching environment where you can explore, innovate, and grow exponentially – academically and personally both.

We are committed to practical learning and provide cutting-edge lab solutions, to enhance your learning journey – including CCNA, CCNP & CCIE, data center, Wireless, Cloud, VMware, F5 -LTM, GTM, ASM, APM, Palo Alto, SD-WAN, Checkpoint, ACI and list goes on.

Leave a Reply

Your email address will not be published. Required fields are marked *