You are on page 1of 10

What is Python File?

A file is a container that stores information, right? In computer systems, a file is


a contiguous set of bytes. Data in a computer system is always stored into files. Files can take different
forms depending on the user requirements like data files, text files, program executable files etc.

Every file contains three main parts:


1. Header: This contains information about the file i.e. file name, file type, file size etc.
2. Data: This is the actual information/content stored in the file.
3. End of file: This is a special character that marks the end of the file.

Also, in a file, a new line character (‘\n’) marks the end of a line or start of a new line.
Types of File
Text File: Text file usually we use to store character data. For example, test.txt
Binary File: The binary files are used to store binary data such as images, video files, audio files, etc.

File Path

A file path defines the location of a file or folder in the computer system. There are two ways to specify a file
path.

Absolute path: which always begins with the root folder


Relative path: which is relative to the program's current working director
Python Open File
You can open file in Python using the built-in function open().
Syntax:
open(filename, access_mode)
Parameters
1. filename:
This is the name of the file we want to open. If the file resides in the same directory as
your program, you can simply specify the file name. But if the file is not present in the same
directory, you need to specify the full path of the file.

2. access_mode:
Access mode specifies what you want to do with the file. The default mode is read mode ‘r’.

It returns the file object. This object is used to read or write the file according to the access
mode. Accesss mode represents the purpose of opening the file. For example, R is for
reading and W is for writing
# Opening the file with absolute path
fp = open(r 'E:\demos\files\sample.txt', 'r')
# read file
print(fp.read())
# Closing the file after reading
fp.close()
Steps For Opening File in Python
Find the path of a file

Decide the access mode

Pass file path and access mode to the open() function


fp= open(r"File_Name", "Access_Mode"). For example, to open and read: fp = open('sample.txt', 'r')

Read content from a file.


Next, read a file using the read() method. For example, content = fp.read(). You can also use readline(), and
readlines()

Write content into the file


If you have opened a file in a write mode, you can write or append text to the file using the write() method.
For example, fp.write('content'). You can also use the writeine() method.

Close file after completing operation


We need to make sure that the file will be closed properly after completing the file operation. Use fp.close()
to close a file.
try:
fp = open(r'E:\reports\samples.txt', 'r')
print(fp.read())
fp.close()
except IOError:
print("File not found. Please check the path.")
finally:
print("Exit")
File Access Modes
The following table shows different access modes we can use while opening a file in Python.
Writing to a File
To write content into a file, Use the access mode w to open a file in a write mode.

Note:

If a file already exists, it truncates the existing content and places the filehandle at the beginning of the file. A new file
is created if the mentioned file doesn’t exist.
If you want to add content at the end of the file, use the access mode a to open a file in append mode

text = "This is new content"


# writing new content to the file
fp = open("write_demo.txt", 'w')
fp.write(text)
print('Done Writing')
fp.close()
Steps for Writing Data into a File in Python
To write into a file, Please follow these steps:

Find the path of a file


We can read a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file.
A relative path contains the current directory and then the file name.

Open file in write mode


Pass file path and access mode w to the open() function. The access mode opens a file in write mode.
For example, fp= open(r'File_Path', 'w')

Write content into the file


Once a file is opened in the write mode, write text or content into the file using the write() method.
For example, fp.write('new text').
The write() method will add new text at the beginning of a file. For an existing file, this new content will replace the existing content. If the file is not already present a new file will be created, and content is written into it.

Close file after completing the write operation


We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.

Append content at the end of the file


Pass file path and access mode a to the open() function to open a file in append mode.
For example, fp= open(r'File_Path', 'a')
Next, use the write() method to write content at the end of the file without deleting the existing content
Create a new empty text file named ‘sales.txt’

# create a empty text file


# in current directory
fp = open('sales.txt', 'x')
fp.close()

Use access mode w if you want to create and write content into a file.

# create a empty text file


fp = open('sales_2.txt', 'w')
fp.write('first line')
fp.close()

You might also like