Python has become one of the world's most popular programming languages. It's used for everything from machine learning to website development and software testing, and can be used by both developers and non-developers, and has produced everything from Netflix's recommendation algorithm to the software that controls self-driving cars. 

Python is a general-purpose programming language, which means it can be used for a variety of tasks such as data science, software and web development, automation, and general task completion. This versatility, combined with its ease of use for beginners, has made it one of the most widely used programming languages today. In this lesson, you will learn all about file handling in python.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

What Is Python File Handling?

Python, like many other programming languages, supports file handling and allows users to read and write files, as well as perform other file-related operations. The concept of file handling in python has spread to many other languages, but the implementation is either complicated or lengthy, but this concept, like many others in Python, is simple and short. 

Python treats files differently depending on whether they are text or binary, which is important. Each line of code contains a sequence of characters that together form a text file. Each line of a file is terminated by a special character known as the EOL or End of Line character, which can be a comma or a newline character. It terminates the current line and informs the interpreter that a new one has begun. Let's get started learning how to work with files.

How to Open a Text File in Python?

We must first open the file before we can perform any operation on it, such as reading or writing. We should use Python's built-in function open for this (). However, when we open the file, we must specify the mode, which represents the purpose of the python open file.

f = open(filename, mode)

How to Create a Text File in Python?

Let's take a look at how to make a file and how write mode works:

In your Python environment, type the following to manipulate the file:

# Python code to create a file

file = open('geek.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

The close() command terminates all resources currently in use and frees the system of this specific program. This will help you in python create files.

Free Course: Python for Beginners

Master the fundamentals of PythonEnroll Now
Free Course: Python for Beginners

How to Append a Text File in Python?

Let's take a look at how the append mode works:

# Python code to illustrate append() mode

file = open('geek.txt','a')

file.write("This will add this line")

file.close()

When working with code, it is intended to provide much cleaner syntax and exception handling. That explains why it's best to use them in conjunction with a statement whenever possible. This is useful because any files opened using this method will be closed automatically after one is finished, resulting in auto-cleanup.

There are also several other commands in file handling that are used to perform various tasks, such as python to write file:

rstrip(): This function strips each line of a file off spaces from the right-hand side.

lstrip(): This function strips each line of a file off spaces from the left-hand side.

How to Read a Python File?

In Python, there are several ways to read a file. We can use file.read to extract a string that contains all of the characters in the file (). The complete code would look like this: 

# Python code to illustrate read() mode

file = open("file.txt", "r")

print (file.read())

Another method of reading a file is to call a specific number of characters, such as in the following code, which will read the first five characters of stored data and return it as a string:

# Python code to illustrate read() mode character wise

file = open("file.txt", "r")

print (file.read(5))

How to Read a File Line by Line in Python?

Using of readlines ()

readlines() is used to read all of the lines at once and return them as string elements in a list. This function is useful for small files because it reads the entire file content to memory and then splits it into separate lines. We can iterate through the list and use the strip() function to remove the newline 'n' character.  

# Using readlines()

file1 = open('myfile.txt', 'r')

Lines = file1.readlines()

count = 0

# Strips the newline character

for line in Lines:

    count += 1

    print("Line{}: {}".format(count, line.strip()))

Data Science with Python

The Ultimate Ticket To Top Data Science Job RolesExplore Course
Data Science with Python

File Modes in Python

Where the following modes of operation are supported:

  • r: open an existing file for reading.
  • w: opens an existing file for writing. If the file already has data in it, it will be overwritten.
  • a: open an existing file for appending. It will not override any existing data.
  • r+: To read and write data into a file. Previous data in the file will not be erased.
  • w+: To write and read data. It will override any previously stored data.
  • a+: To append and read data from a file. It will not override any existing data.
  • The open command opens the file in read mode, and the for loop prints each line in the file through open file python. 
Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

File handling in Python is fairly simple because most basic operations require only a single line of code to complete. The concepts covered in this tutorial should assist you in creating your own files and adding functionality and operability to them. This will come in handy when you're trying to create an application by simplifying the process and tailoring it to your specific requirements. You should now be able to use these file operations to easily develop applications with Python. To learn and implement file handling in Python, and get an in-depth understanding of Python, enroll in Simplilearn's comprehensive Python Training program today!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.