Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Python File Handling

by suresh

Python does support File handing. I mean, Python provides various functions that allow us to create a file, open file, read the data, and write data to a file. Unlike other languages, Python handles files differently. Python treats Files as text or binary based on the data, and each line has to terminate with an End Of Line characters like newline, comma, etc.

Python provides an important function called open to work with files. The Python File open function accepts two parameters, and they are file_name and mode. The syntax of this Python file open function is

f_open = open(“File_Name”, “mode”)

The Python mode is an optional argument. There are four different modes in Python for opening a file.

  • r – It means, Read Mode, and this is the default mode of Python file open. It opens an existing file for reading if there is no file, then it throws an error.
  • r+ – This is for both reading and writing mode.
  • a – Means Append. If the file exists, then this opens that file and appends the data to the existing content. If there is no file, then it creates a new file with the name we specified.
  • w – Means Write mode. It opens a Python file in write mode and overrides the existing content with new content. It creates a new file if the file doesn’t exist.
  • x – Use this to create a new file. It throws an error if the file exists.
  • Apart from these modes, you can also specify the type of data that the file has to handle. I means binary data or text mode
  • t – Text Mode, and this is the default mode.
  • b – Binary mode.
f_open = open("PythonSample.txt")

The above code is equal to f_open = open(“PythonSample.txt”, “rt”)

Python File Operations

The following list of examples helps to Create a New File in Python, Open, Rename it, Delete. Next, write text to a File, File close, append, write, read options that are available in Python. To demonstrate most of these Python file functions, we use this text file

Python File Examples

Python Open File

In Python, you can open a file, either specifying the file name or the full path. The full name opens the file in the current working Directory. However, using the full path, you can access files at any directory. Before we start, let me use the listdir function to get the files list in the current directory. 

import os

print(os.getcwd())
print(' ')
print(os.listdir())
Python File Open

In Python, you can open a file, either specifying the file name or the full path. 

f_open = open("PythonSample.txt")

Or  use full path

f_open = open("C:/users/Document/PythonSample.txt")

Python read file

The Python read file function is to read the data inside a file. It is a simple Python File example, which opens a sample text file in the read mode. Next, we used the read function to read data inside that text file.

f_open = open("PythonSample.txt", "r")
print(f_open.read())
Python Read File

While working with string data, you can use the read function with a parameter to restrict the number of characters returned by the read function. For example, read(5) reads the first five characters or read(10) read the first 10 characters.

f_open = open("PythonSample.txt", "r")
print(f_open.read(5))
print(f_open.read(2))
Python Read File 1

As you see, the first read statement prints the first five characters. Next, read is printing the next two. If you want to print the first 10, then you have to close and reopen the file.

f_open = open("PythonSample.txt", "r")
print(f_open.read(5))

f_open = open("PythonSample.txt", "r")
print(f_open.read(8))
Python Read File 2

Python Read file using For Loop

You can also use loops to read all the data in a sequence. For instance, the example below uses For Loop to read each line available in this text file.

f_open = open("PythonSample.txt", "r")
for char in f_open:
    print(char)
Python Read File 3

This example loop over the complete file in the sample text file and prints each and every line.

f_open = open("PythonSample.txt", "r")
for line in f_open:
    print(line, end = '')
Python Read File 4

Python readline function

The Python readline function reads the complete line before the end of line character. This example opens a file and reads the first line from it.

f_sample = open("PythonSample.txt", "r")
print(f_sample.readline())
Python readline function 1

If you want to read two lines, then call the readline function twice and so on. Let me print three lines.

f_sample = open("PythonSample.txt", "r")
print(f_sample.readline())
print(f_sample.readline())
print(f_sample.readline())
Python readline function 2

You can use this readline function to read or print the required line. The below readline function code print the second line from a text file.

If you use the readline function along with an argument, then it behaves the same as the read function with a parameter. I mean, readline(2) = read(2)

f_sample = open("PythonSample.txt", "r")
print(f_sample.readline(2))
print()
 
f_sample = open("PythonSample.txt", "r")
print(f_sample.read(2))
Python readline function 3

Python readlines function

In Python, we have one more function called readlines(). It reads data from the given text file, and prints all the data in a list format. It separates each line with a proper separator.

f_sample = open("PythonSample.txt", "r")
print(f_sample.readlines())
Python readlines function

Python file close function

As the name suggests, Python file close function closes an already opened file. Although Python has a Garbage Collector to close the files, you should not rely entirely on this. It is always a good practice to close the open file.

Here, we opened a file, read a single line, and then closed that file.

f_sample = open("PythonSample.txt", "r")
print(f_sample.readline())
f_sample.close()
Python file close function 1

Let me print another line from that closed file. 

f_sample = open("PythonSample.txt", "r")
print(f_sample.readline())

f_sample.close()
print(f_sample.readline())

You can notice the error thrown by Python shell.

Python file close function 2

The above program show the use of the close method. However, it is not advisable to use the way that we showed above. In real-time, you have to use with statement to close the opened files properly. Or, some people say, we can go with try finally block. We show you both.

Python File using Try finally

try:
    f_sample = open("PythonSample.txt", "r")
    print(f_sample.read())
finally:
    f_sample.close()
Python file Try Finally

Python with Statement

The Python with statement makes sure that every file opened by this closed irrespective of the errors.

with open("PythonSample.txt", "r") as f_sample:
    print(f_sample.read())
f_sample.close()
Python With File 1

Python with statement is not about closing the file. You can use this with statement to open a file in any mode. I mean, you can use this to read data, write data so on. Most importantly, we use this in the case of file manipulations, where we have to execute multiple statements. This statement holds them in a block so that we can write multiple statements in that block.

with open("PythonSample.txt", "w") as f_sample:
    f_sample.write("First Line")
    f_sample.close()
 
with open("PythonSample.txt", "r") as f_sample:
    print(f_sample.read())
f_sample.close()
Python With File 2

Python File Write

Python provides the write function to write content or data to a file. Before we get into the Python write function example, I assume you remember what I said earlier. You have to use either a mode for append or w for write mode.

This example opens the Sample text in write mode and writes a welcome message. Next, we opened that file to print the data.

f_demo = open("PythonSample.txt", "w")
f_demo. write("Welcome to Tutorial gateway")
f_demo.close()
 
# Let me open the file and check
f_demo = open("PythonSample.txt", "r")
print(f_demo.read())
Python File Write 1

This time, we write multiple lines of code using the write function.

f_writedemo = open("PythonSample.txt", "w")
f_writedemo. write("Python")
f_writedemo. write("\nTutorial gateway")
f_writedemo. write("\nHappy Coding!")
f_writedemo. write("\nHi \nHello \nCheers")
f_writedemo.close()
 
# Let me open the file and check
f_writedemo = open("PythonSample.txt", "r")
print(f_writedemo.read())
Python File Write 2

We have been working on this file from the beginning, and you know the data. However, this write function erased everything and returned this Welcome message.

Python provides writelines function to write data to files. This function accepts a list as an argument so, you can write a list of items at one go. I mean, without using multiple write functions.

f_writelinesdemo = open("PythonSample.txt", "w")
text = ["First Line\n", "Second Line\n", "Third Line\n", "Fourth Line"]
f_writelinesdemo. writelines(text)
f_writelinesdemo.close()
 
# Let me open the file and check
f_writelinesdemo = open("PythonSample.txt", "r")
print(f_writelinesdemo.read())
Python File Write 3

Python File append

This time, we are opening a file in append mode, and check what happens after writing a hello message

f_demo = open("PythonSample.txt", "a")
f_demo. write("\nHell World!")
f_demo.close()
 
# Let me open the file and check
f_demo = open("PythonSample.txt", "r")
print(f_demo.read())
Python File Append

Write to a File using Loop

You can also use the for loop to write multiple lines of information. Here, we are sampling writing 10 lines in a Sample10 text file.

f_loopdemo = open("Sample10.txt", "w")
for i in range(1, 11):
    f_loopdemo.write("This is the %d Line\n" %(i))
f_loopdemo.close()
 
# Let me open the file and check
f_loopdemo = open("Sample10.txt", "r")
print(f_loopdemo.read())
Python File Write using For Loop

Create a New File in Python

Until now, we are working with the existing files. However, you can create your own file using the read method. For this, you have to use either x for creating a new file, a mode, or w mode. All these three modes create a new file, but the last two modes are different.

f_create = open("NewFile.txt", "x")

Let me create another file in Python and write something to it. So, you can see the New file along with the text. This program creates a Sample1 text file and writes a Python Program string and closes it. Next, we opened that file in the read mode and printing the data from it.

f_create = open("Sample1.txt", "x")
f_create.write("Python Program")
f_create.close()
 
# Open the Sample1 file
f_create = open("Sample1.txt", "r")
print(f_create.read())
Python File Create 1

It uses the w for write mode to create a new file and writes something to it.

f_wcreate = open("Sample2.txt", "x")
f_wcreate.write("Python Tutorial")
f_wcreate.close()
 
# Open the Sample1 file
f_wcreate = open("Sample2.txt", "r")
print(f_wcreate.read())
Python File Create 2

We are using the open function along with a mode – append mode.

f_acreate = open("Sample3.txt", "x")
f_acreate.write("Tutorial Gateway")
f_acreate.close()
 
# Open the Sample1 file
f_acreate = open("Sample3.txt", "r")
print(f_acreate.read())
Python File Create append mode

Rename a File in Python

To rename a file within a directory, you have to import the os module. Within the os module, we have a rename function that helps us to rename existing files in a directory.

Let me use this Python file rename function to rename Sample2.txt file to NewSample.txt. Next, we opened that renamed file to see the data inside that file.

import os
os.rename("Sample2.txt", "NewSample.txt")
 
f_sample = open("NewSample.txt", "r")
print(f_sample.read())
Python File Rename

Delete a File in Python

To delete a Python file from a directory, you have to import the os module. Within the os module, we have a remove function that helps us to remove files from a directory. Let me use this Python file remove function to delete the Sample3.txt file that we created before.

import os
os.remove("Sample3.txt")
Python File Delete 1

It works like a charm; however if you try to delete a file that doesn’t exist with throw an error. Let me remove the Sample3.txt that we deleted before.

When you run, it throws an error: FileNotFoundError:[Errno 2] No such file or directory: ‘Sample3.txt’. To avoid these kind of errors, it is advisable to check whether the file exists or not.

import os
if os.path.exists("Sample3.txt"):
    os.remove("Sample3.txt")
else:
    print("Hey! No such file exists")
Python Delete File 2

Python seek and tell Functions

These are the two functions to find the pointer position in a file. 

  • tell(): It tells you the current pointer position. 
  • seek(): To set the pointer position to a specific position. 
with open("PythonSample.txt", "r") as f_sample:
    print("File Pointer Initial Position : ", f_sample.tell())
    print(f_sample.read())
    print("Current File Pointer Position : ", f_sample.tell())
     
    f_sample.seek(22)
    print("\nCurrent File Pointer Position : ", f_sample.tell())
 
f_sample.close()
Python File seek

File Attributes

Python provides the following file attributes to get the information about the file that you are working with.

  • file.name: It returns the name of the file.
  • file.mode: On what mode you opened this file. For instance, r mode, w mode, etc
  • File.closed: returns True if the given file closed otherwise, False. 
f_open = open("PythonSample.txt", "r")
print(f_open.read())

print('\nFile Name = ', f_open.name)
print('File Mode = ', f_open.mode)
print('File closed? = ', f_open.closed)

f_open.close()
print('\nFile closed? = ', f_open.closed)
Python File Attributes

Placed Under: Python

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021· All Rights Reserved.
About | Contact | Privacy Policy