• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

7 File Handling Operations in Python Explained with Programming Examples

Aniruddha Chaudhari/31461/2
CodePython

File handling is a very crucial concept in Any programming. The file is used to store the text data which can be used by your program.

Want to learn how to create, open read and write in Python?

Here is a complete file handling Python tutorial for you.

Table of Contents

  • File Handling in Python
    • How to Create a File in Python?
    • How to open the File in Python?
    • How to Read File in Python?
    • How to Read Line-by-Line File into List?
    • How to Write a File in Python?
    • How to Close a File in Python?
    • How to Delete File in Python?
  • What are the different File Modes in Python?
  • Best Practices for File Handling
  • Problems for File Handling in Python for Practice [Homework]
  • Conclusion

File Handling in Python

There are multiple operations to perform such as creating, reading, writing and updating file content.

Let’s see how to do those file handling in Python with open() function with programming examples.

How to Create a File in Python?

We are using open() built-in function to create a file.

open("myFile.txt", "w+")

This is the single open method that will create the file if it is not present.

To add content in the newly created file, you should open the file in write mode.

There are two arguments are passed to the open() builtin function- the name of the file and mode the file (w+).

Here,

w – Create the file in write mode
+ – Create a file if it’s not present in the current directory.

Note: File will be created in the current directory (the directory where your Python code is running).

How to open the File in Python?

You can use the same code as I have mentioned for creating a file.

open("myFile.txt", "r") as fObj

How to Read File in Python?

First, open the file in reading mode “r” and then read the content from the file.

open("myFile.txt") as fObj 
    data = fObj.read() 
    print(data)

All the file contents will be saved in a single string object.

You can also use “with” statement with an open file.

with open("myFile.txt") as fObj:
    data = fObj.read()
    print(data)

There are multiple benefits of using “with” statement. We will see the benefits in the later part of this tutorial.

Now a day it has become standard practice opening file “with”

How to Read Line-by-Line File into List?

Rather than reading complete file text in a single string object, what if you want to read the file line-by-line?

with open("myFile.txt") as fObj:
    liData = fObj.readlines()
    print(liData)

Each line in the file will be saved as one element in the list. So the size of the list will be the same as the number of lines in the file.

Reading a file in the list is very important when you want to manipulate the text in each line of the file. After reading file content in the list, you just need to loop over each element in the list and perform your desired operation.

Python provides multiple list operations which makes your work associated with the file operation even easier.

How to Write a File in Python?

Two operations. First, open the file and then write the text content in it.

The file object has a write() method associated with it to write the text in the file.

with open("myFile.txt", 'a+') as fOut:
    fOut.write("my data to add."+'\n')

Here,

  • We are opening the file in “a+” mode so that, it will append the new content at the end of the file.
  • The “\n” character is used to add the next in a new line.

How to Close a File in Python?

It is always good practice to close the file after using it.

Python code to close and delete the file object if you are not performing any file operation further.

open("myFile.txt", "r") as fObj
#perform file operations
fObj.close()

Otherwise,

Use “with” statement while opening the file. You don’t need to explicitly close the file object. As soon as the pointer goes out of the with statement block, the file object will be closed.

with open("myFile.txt", "r") as fObj:
    #perform file operations
#file is closed automatically

How to Delete File in Python?

Many times you need to delete the file instead of closing it.

If you try to delete the file which is not present, it will throw an I/O error.

Always check the file existence. If the file present, delete it.

import os
#delete file if it exists.
if os.path.exists("yourFile.txt"):
    os.remove("yourFile.txt")

The “path” and “remove” objects are described in the os module. So, you have to import the “os” module.

What are the different File Modes in Python?

There are multiple modes to open the file.

“r” mode: Open the file in reading mode. The pointer will be assigned at the beginning of the file. It will throw an error if the file does not exist.

“r+” mode: Open the file for reading writing. The pointer will be assigned at the beginning of the file to read and write a file. It will throw an I/O error if the file not exist.

“w” mode: Open the file in write mode. The pointer will be assigned at the beginning of the file and it will overwrite all the contents in the file.

“w+” mode: Open the file in read-write mode. All the data in the existing file will be truncated (delete and throw away) and overwritten.

“a” mode: Open file in append mode. Instead of overwriting original content, in this mode, you can append the new content at the end of the file. If the file is not present, a new file will be created with the file name mentioned.

“a+” mode: Open the file in append mode. If the file does not exist, it will create a new file. It will append the new content at the end.  The existing content in the file will be intact.

As we can use both ‘r+’ and ‘w+’ mode for reading and writing a file, they are more confusing. Read the difference between ‘r+’ and ‘w+’ mode in Python.

What is the default file mode?

If you don’t mention the file mode while opening the file, ‘r’ will be the default file mode

Best Practices for File Handling

1. Assign File Name to the Variable:

If you are reading and writing files multiple times, always create the variable for the file name. So you don’t need to assign file names every time in your program.

FILE_EMP = "empFile.txt"
with open(FILE_EMP) as fEmp: 
    liEmp = fEmp.readlines()

Even in the future if you need to change the file name, you just have to change the new file name in a variable. Otherwise, you have to update the text file everywhere you have used through your project. Its time consuming and not good practice.

2. Choose Right Mode to Read, Write or Append File

If you don’t want your program to write the file, always open the file only for reading.

The opening file in write mode will erase the original content in the file and will add new content. If you want your program to append the new content at the end of the file, always open a file in append mode.

3. Closing file object after using it. 

Otherwise, it is always a good choice to use” with” statement while opening the file.

Problems for File Handling in Python for Practice [Homework]

You can not learn all these file operations without writing code. So here are some of the problems you can practice and learn file handling.

1. Write a Python program to remove all the duplicates lines from the file.

Hint: Read the file line-by-line in the list and find all the unique elements in the list. Write back all the content from the list in the file.

2. Write a Python program to randomly select any line from the file.

Hint: Read the file line-by-line in the list and randomly select elements from the list.

3. Write a Python program to add a given line to file if it is not already there.

Hint: Read the line-by-line file into the list. Search if the given text is present. If it is not there, append the new content inside the file as a new line.

4. Write a Python program to find the longest line in the file.

Hint: Hint mentioned in the above three problems is sufficient to solve this problem as well.

You can also submit your homework with me. I will share your program on our portal.

Conclusion

This is all about a complete tutorial for file handling in Python. You have learned to create, to open, to read, and to write a text file. If you find any difficulty while handling the file or Python code mentioned in this tutorial, write in the comment.

For further, explore reading and writing CSV files in Python.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    ASMITA
    June 13, 2019 at 12:34 pm

    When I am trying to read contents from my file,the single set of 2 statements is getting printed 5 times. Please help

    • Reply
      Aniruddha Chaudhari
      June 13, 2019 at 12:51 pm

      Can you paste your code here?

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard