Piton

Reading and Writing Files with Python

Reading and Writing Files with Python

Files are used to store and organize data on a disk. We often use files when we need to store data permanently on a hard disk. For example, say we are building a software system that maintains student records. Now, we need to store the student data permanently for future use. For this purpose, we can use files to store data, and later on, we can open these files and access the stored data at any time.

Reading and writing files are very common functions in Python. It is easy to create, read, and edit files in Python. Python comes with built-in functions for reading and writing files. You can open, write, and read files using the Python built-in functions. The file operations are performed in the following sequence:

Using Python, you can create text files and binary files. Text files store data in the form of characters and each line ends in a newline character ('\n'). In binary files, data is stored in the form of bytes (1 and 0).

In this article, you will learn:

Different File Modes in Python

Modes in Python describe the type of operation to be performed on the file. When opening a file, you must specify the mode. Every file has a file handle. The file handle acts like a cursor that specifies where to write and read data. It is a type of location pointer. The following include some of the different access file modes in Python:

Mode Description
r Opens the file in reading mode. This mode is selected by default if you do not define any mode while opening the file in Python.
w Writes a file. This mode creates a file if the file does not exist already and overwrites the data in the file.
r+ Used to read and write the file. It shows an error if the file does not exist.
a Opens the file in append mode. The file handle is located at the end of the file. This mode does not overwrite the existing data but starts writing data at the end of the file. A new file is created if the file does not exist.
a+ Opens the file for reading and writing. This opens the file in append mode for writing. The data is inserted at the end of the file. A new file is created if the file does not exist.
t Opens the file in text mode.

How to Open a File

To open a file in Python, use the built-in open() function. The open() function takes two arguments as an input, i.e., the name of the file and the mode of operation. This function returns the file object as an output. There is no need to import any module to use the open() function. The following is the syntax of the open() function:

file_object = open(“file_name”, “mode”)

Here, 'file_name' represents the name of the actual text file, while 'mode' represents the file access or file operation mode. You can also place r before 'file_name,' if the file name includes special characters. The r is placed as follows:

=file_object = open(r“file_name”, “mode”)

For example, the file name could be: “F:\newfolder\myfile.txt”

How to Create a File

The open() function can be used to create files in Python. Use the append mode (a) inside the open() function to create the file. Create a file using the code given below:

file = open("sample.txt","a")

Here, a new file object is created. The file object is named “file.” The name of the newly created text file is “sample.txt.” The text file is opened in append mode. It will create the new file if the file does not exist already. After creating the file, you must close the file in the following way:

file.close()

The built-in close() function is used to close the file.

How to Write Data to a File

There are two functions in Python used for writing data in a file:

  1. write()
  2. writelines()

The write() function is used to write single line or single string data to a file, while the writelines() function is used to write multiple lines of data to a text file. Let us see some examples of writing data to a file.

Using the write() Function

In this example, we are using the write() function to write data to a file. The file is opened in writing mode. “\n” is placed to specify the end of the line.

# creating a new file object and opening a file in writing mode
file=open("sample.txt","w")
# writing single line to a file
file.write("Welcome to the linuxhint \n")
# writing another single line to a file
file.write("Welcome back")
#closing the file
file.close()

Output

The lines have been written in the text files.

If we open the file in writing mode and ask the write() function to write more lines to the file, it will overwrite the previous data and new data will be added into the text file.

# creating a new file object and opening a file in writing mode
file=open("sample.txt","w")
# writing single line to a file
file.write("Hello Everyone \n")
# writing another single line to a file
file.write("This is the replaced string")
#closing the file
file.close()

Output

In the output, it can be seen that the previous data is replaced and new data is added in its place in the text file.

If we want to keep both the previous and the new data in the file, then we can open the file in append mode, like this:

# creating a new file object and opening a file in append mode
file=open("sample.txt","a")
# writing single line to a file
file.write("Hello Everyone \n")
# writing another single line to a file
file.write("This is the replaced string\n")
# writing another new single line to a file
file.write("This is the newly added string string\n")
#closing the file
file.close()

Output

Using the writelines() Function

The writelines() function is used to write multiple lines in a text at once, as follows:

# creating a new file object and opening a file in writing mode
file=open("file1.txt","w")
# storing multiple string data in a variable
str = ["Hello everyone\n","Welcome to the linuxhint\n","we are using writelines function\n"]
# using writelines functions to write data in a file
file.writelines(str)
#closing the file
file.close()

Output

How to Read a File

To read a file in Python, first, open the file in reading mode. There are three built-in functions in Python for reading a file. These include the following:

  1. read()
  2. readline()
  3. readlines()

read(): Used to read the data from a file; returns the whole data in the form of string.

readline(): Reads a line of data from a file; only returns the first line.

readlines(): Reads all existing lines from a file; returns it in the form of a list.

The seek() function is used to change the file handle position. When reading data in the file, the file handle positions itself at the end of the file. Thus, a file handle is like a cursor, with the seek() function as the means to move the cursor.

Let us see an example of reading data from the file.

# opening a file in read mode
file=open("file1.txt","r")
# using read() function to read the data from the file
# storing the lines in a variable
data=file.read()
# printing the data
print("This is the output of read() function: \n")
print(data)
# using seek() function to bring the file position in start
file.seek(0)
# using readline() function to read the data from the file
# storing the lines in a variable
data=file.readline()
# printing the data
print("This is the output of readline() function: \n")
print(data)
# using seek() function to bring the file position in start
file.seek(0)
# using readlines() function to read the data from the file
# storing the lines in a variable
data=file.readlines()
# printing the data
print("This is the output of readlines() function: \n")
print(data)
#closing the file
file.close()

Output

Conclusion

It is often necessary to store information or data to a file. In Python, you can easily create, write, and read files using the Python built-in functions. There is no need to import other modules into your program when you want to read, write, and create files. You can also use multiple built-in access modes while using the files. In this article, we have explained how to read and write files in Python with some simple examples.

Battle For Wesnoth 1.13.6 Development Released
Battle For Wesnoth 1.13.6 released last month, is the sixth development release in the 1.13.x series and it delivers a number of improvements, most no...
Cum se instalează League Of Legends pe Ubuntu 14.04
Dacă ești fan al League of Legends, atunci aceasta este o oportunitate pentru tine de a testa rula League of Legends. Rețineți că LOL este acceptat pe...
Instalați cel mai recent joc de strategie OpenRA pe Ubuntu Linux
OpenRA este un motor de jocuri de strategie în timp real Libre / Free care recreează primele jocuri Westwood, cum ar fi clasicul Command & Conquer: Re...