How To Handle Files Through Python

Introduction

Nowadays Python has emerged as a totally famous and effective language due to its excellent overall performance and huge variety of features by which we are able to use Python in various fields inclusive of gadget studying, picture processing, web designing, 3-D objects, GUI based computer packages, medical computation, video games, OS, making another language and community programming. Python is an open-supply item-orientated interpreted high-level language.

Writing Python Program for Beginners

Step 1

Open an editor like Notepad, Sublime, and VS Code.

Step 2

Write the code or instructions.

Step 3

Save it with filename name having extension .py.

Step 4

Run the file using Command Prompt or IDLE. If you are running through Command Prompt go to the directory where the program is saved then type filename.py.


Fig. 1: Code written in Notepad before saving it as extension .py.


Fig. 2: After saving in extension .py, running code through command prompt.

File Handling

Python supports file handling also and accesses users to perform open, read, and write, along with many various operations. A File is a collection of data stored in a secondary storage device like a Hard Disk. Files are stored in a tree or hierarchical structure which makes it easy to retrieve and access the files from Hard Disk as required. There can be only one top of the tree which is called Root Node or Root Folder below this there are other files and folders which further contain more files and folders. The path of each file is identified from the root folder for example drivers in windows system C:\, D:\, etc. The path of the file is called Pathname.
For example, D:\ Programming\ Python\ Program1.py is Pathname whereas, Program.py is the destination file, Python is the sub-folder, Programming is the folder, and D:\ is the root folder.
Character (\) used to separate file names is called Delimiter. In rare cases such as Solaris OS ‘/’, this delimiter is used.

Pathname which specifies from root to exact location of the file as shown in the above example is called Absolute Path whereas, pathname starts with respect to the current working directory and is called Relative Path for example Python\Program1.py.

There are two types of files supported in Python, text files and binary files. Binary files are those files that contain any data encoded in binary 0&1 for processing and storage purposes.
There are many in-built functions in Python to manipulate files.

1. Creating & Opening File

Python has a built-in function open() to open the existing file or to create a file if it doesn't exist in the directory. This function creates a file object in memory. There is an upper limit that a file can be opened, if that limit is exceeded then the file may crash or run in an unexpected manner. Opening files unnecessarily makes lots of memory wastage and may also lead to the chance of corrupting a file or data loss.
The syntax of this function is fileobj=open(“file name with extension”, ”mode of access”) here write the file name with an extension which you want to access, and in the mode of access indicates that the opened file is used for which purpose like reading, write, append, etc.

Example

file=open(“File.txt”,”rb”)
  print(file)

In four access mode r, rb, r+, rb+ if file is not created and it will show an error.

File Object Attribute

When a file is opened successfully file object is returned, using this we can access any information regarding the file.

  • fileObj.closed: Returns Boolean value whether the file is closed or not.
  • fileObj.mode: Return access mode in which the file is opened.
  • fileObj.name: Return the name of the file.

Example

file=open(“File.text” , ”wb”)  
	  print(“Name of file:”, file.name)
	  print(“File opened in:”, file.mode, “mode”)
	  print(“File is closed:”, file.closed)

Some Access Modes for Creating or Opening a file

•r

Default mode of accessing file opens only for reading only. The file pointer is positioned at the start of the file.

•rb

This mode opens the file for reading in binary format. Same as the ‘r’ The file pointer is positioned at the start of the file.

•r+

Opens a record for both analyzing and writing. Previous data will not be deleted.

•rb+

Opens file for both reading and writing in binary format.

•w

Open file only for writing. In these two cases are possible if the file does not exist, a new file is created otherwise if the file is already in existence the previous data stored in it will be overwritten.

•wb

Opens file for writing in binary format. Same as ‘w’ two cases are possible if the file does not exist, and a new file is created otherwise if the file is already in existence the previous data stored in it will be overwritten.

•w+

It opens files for both reading and writing. If a new file is created by this it will be used for both reading and writing but if an existing file is opened previous data stored in it will be overwritten.

•wb+

Opens file for both reading and writing in binary format. Same as ‘w+’ if a new file is created by this it will be used for both reading and writing but if an existing file is opened previous data stored in it will be overwritten.

•a

Opens file for appending. The file pointer is placed at the end of the file if the file already existed otherwise a new file is created for writing.

•ab

Opens file for appending in binary format. Same as ‘a’ File pointer is placed at the end of the file if the file has already existed otherwise a new file is created for writing.

•a+

Opens file for reading and appending. The file pointer is placed at the end of the file if a file already exists otherwise a new file is created for reading and writing.

•ab+

Opens file for reading and appending in binary format. Same as the ‘a+’ file pointer is placed at the end of the file if a file already exists otherwise a new file is created for reading and writing.

2. Closing the file

There is a function close() as the name suggests its behavior is to close a file object. Once a file object is closed any operation in the file regarding that closed file object cannot be performed.

Syntax of this is fileObj.closed(). This function frees up system resources like file lock, file descriptors, etc. regarding the file. After closing the file, if there is any attempt to access that file without opening there will an error.

Python has a garbage collector to clean up the unreferenced objects but still, you should use the close method when not needed and release the resources consumed by it.

3. Reading the file

read() function is used to read the string of a file. The string can be any alphabet, number, special character, or symbol. The syntax of this is fileObj.read(count). This function begins reading from the beginning of the file. In this count, the parameter is optional and specifies the number of bytes to read from a file. If the count has a negative value or the count value is not written then this function reads the entire context of the file till the end of the file.

Example

file=open(“program1.txt”,”r”)
	 print(file.read(16))

Output: Hello Programmer

read() returns newline as ‘\n’.

In four access mode r, rb, r+, rb+ if file is not created it will show an error.

readline() function is used to read a single line from a record. at the end of the record, an empty string is returned. In this we have to pass an argument of readline() every time for every line to ease this there is a method same as this readlines() in which all the lines of the files are read at a time.

There is a method list() which is also used to display the entire file at a time. In this, we just need to pass the file object argument. Don’t get confused with list=[] these both are different.

Example

file=open(“program1.txt”,”r”)
     print(list(file))

Output

Hello Programmer Welcome to the C# Corner

4. Writing and Append the file

write() function is used to write the string of an already opened file. The syntax of this is fileObj.write(string).

Example

file=open(“program1.txt”,”w”)
	  file.write(“Hope you all are enjoying”)

writelines() is used to put in writing a list of strings.

Example

file=open(“program1.txt”,”w”)
	  lines=[“Nice to see you”, “How are you doing?”,”Hope you will enjoy alot”]
	file.writelines(lines)

After storing data we can access the file again and append more data to it. For appending we need to open the file in ‘a’,’ ab’, ’a+’, and ’ab+’ mode. We need to be careful if we open in ‘w’,’ wb’, ’w+’, and’wb+’ mode then stored data content will be overwritten.

Example

file=open(“program1.txt”,”a”)
	  file.write(“Python is a powrful language”)

5. Renaming and Deleting file

There is a module in Python ‘’os’’ by which we can perform file processing operations like renaming and deleting. For this, we want to import the os module.

rename() function takes two arguments current file name and new file name.

Syntax is os.rename(”current name”, “new name”)

Example

 import os
	  os.rename(“file.txt”,”Programmer.txt”)

remove() function used to delete, takes a file name as an argument. Syntax is os.remove(“filename”)

Example

import os
	  os.rename(“file.txt”,”Programmer.txt”)

Some functions used for File Handling

fileno()

Returns the file number of the file. It returns an integer.

Example

file=open(“program1.txt”,”w”)
	  	  print(file.fileno())

flush()

Flushes the write buffer of the stream.

Example

file=open(“program1.txt”,”w”)
            file.flush()

isatty()

Returns Boolean value whether file stream is interactive or not.

Example 

 file=open(“program1.txt”,”w”)
            file.write(“Hello”)
 print(file.isatty())

Output: False

tell()

Tells the current position of the file pointer.

Example 

file=open(“program1.txt”,”r”)
            print(file.tell())

seek()

Use to change and set the new position of the file pointer. Take two arguments new offset and old offset.

Example 

file=open(“program1.txt”,”rb”)
 print(file.seek(3,1)

truncate(n)

Resize the file to ‘n’ bytes.

Example 

file=open(“program1.txt”,”w”)
file.write(“Hello World”)
file.truncate(5)
file=open(“program1.txt”,”r”)
print(file.read())

Output: Hello

Summary

Python emerged as the most powerful and successful language we can use in various areas. Python is an open-supply item-orientated interpreted high-level language. Python supports report handling also and accesses users to carry out open, read, and write, alongside many numerous operations. A document is a collection of information stored in a secondary storage device like a hard disk. Documents are stored in a tree or hierarchical structure which makes it easy to retrieve and access the documents from the hard disk as required. open()  is used to create or open files creates a file object in memory and takes two arguments the file name with an extension that you want to access, and the mode of access. There are many modes of access like “r”, ”rb”, ”r+”, ”rb+”, “w”, ”wb”, ”w+”, ”wb+”, “a”,” ab”, ”a+”, ”ab+”. Mode of access which contains ‘b’ like “rb, rb+, wb, wb+” opens the file in binary form or else in normal form. Mode of access indicates that the opened file is used for which purpose like reading, writing, appending, etc. In four access modes r, rb, r+, rb+ if the file is not created and it will show an error. close() is used to close the file and once the file object is closed any operation in the file regarding that closed file object cannot be performed. read() function is used to read the string of a file and begins reading from the beginning of the file.

The readline() function is used to read a single line from a record whereas in readlines() all the lines of the files are read at a time. write() function is used to write the string of an already opened file. writelines() is used to put in writing a list of strings. For appending we need to open the file in ‘a’,’ ab’, ’a+’, and ’ab+’ mode. We need to be careful if we open in ‘w’,’ wb’, ’w+’, and’wb+’ mode then stored data content will be overwritten. Os module performs file processing operations like renaming and deleting, we need to import this module. Besides these there are many other functions that are used for file handling like fileno(), flush(), isatty, truncate(n), tell(), and seek().


Recommended Free Ebook
Similar Articles