Skip to content

How to read and write to a file in Python

How to read and write to a file in Python

In this tutorial we will learn how to read and write to a file in Python . Further reading this tutorial we recommended to read about File handling in Python – An Intro for beginners .

How to read a file in Python

To read the contents of any file, we need to open the file in “r” mode. When opening a file in “r” mode we need to make sure that the file exists otherwise the program will raise error. Here we will use the file “hello.txt” and we will keep the file in the current folder where we are working now .

Here is the content of hello.txt –

Hello, World1!
Hello, World2!
Hello, World3!
Hello, World4!
Hello, World5!

Python File read() method

With the read method we can read the entire content of any file.

Syntax of read() method

file_Object.read([count])

Parameters of read() method

count = Optional , takes an integer and returns that many character . If we do not specify count parameter then it returns full content .

Return type of read() method

It returns a string .

Examples of Python File read() method

Example 1: Read full content of a file in Python

#open a file
fp=open("hello.txt","r")

#read the file
x=fp.read()
print(x)

#closing the file
fp.close()
Hello, World1!
Hello, World2!
Hello, World3!
Hello, World4!
Hello, World5!

In the above code we did not give anything as an argument in the read() method, so we got the full content of the hello.txt file as output .

Example 2: Read some character from a file in Python

fp=open("hello.txt","r")

# reading first 4 character
x=fp.read(4)
print(x)

# freading next 6 character
x=fp.read(6)
print(x)
fp.close()
Hell
o, Wor
  • In the above code, we have given 4 for the first time as argument in read() method, so we got the first 4 letters of the whole content as output . Now after reading 4 letters position of the file pointer is at 5th letter of the file .
  • Then we have given 6 as argument in read() method, so we got the next 6 letters as output.

Python File readline() method

With the help of readline() method we can read one line of any file. The readline() method also returns a string.

Syntax of readline() method

file_Object.readline(size)

Parameters of readline() method

size = Optional . It is an integer number specifying the number of characters to return . Default value is -1 which means the whole line .

Return type of readline() method

It returns a string.

Examples of Python File readline() method

Example 1: Read a file in Python line by line

fp=open("hello.txt","r")

#printing the first line
x=fp.readline()
print(x)

#printing the second line
x=fp.readline()
print(x)
fp.close()
Hello, World1!

Hello, World2!
  • In the above code after applying the readline() method for the first time , it prints the first line of the whole content .
  • Then we have applied the readline() method again . After applying the readline() method for the second time, it prints the next line i.e. the second line.

Example 2:

fp=open("hello.txt","r")

# printing 4 characters from first line
x=fp.readline(4)
print(x)

# printing rset part of the first line
x=fp.readline()
print(x)

# printing the second line
x=fp.readline(-1)
print(x)
fp.close()
Hell
o, World1!

Hello, World2!
  • In the above code after applying the readline() method for the first time with argument as 4 , it prints the first 4 characters from the first line of the whole content . Now the file pointer stands at 5th character of the first line .
  • Then we have applied the readline() method again without any argument . So it has printed rest part of the first line . Now file pointer stands at 1st character of the second line .
  • After that we have applied the readline() method again with argument as -1. So it has printed the second line .

Python File readlines() method

The readlines method splits the file content at every newline character and returns a list .

Syntax of readlines() method

file_Object.readlines(hint)

Parameters of readlines() method

hint = Optional . An integer number specifying the minimum number of characters to return . default is -1 which means all the lines will be returned .

Return type of readlines() method

It returns a list .

Examples of Python File readlines() method

Example 1:

fp=open("hello.txt","r")
x=fp.readlines()
print(x)
fp.close()
['Hello, World1!\n', 'Hello, World2!\n', 'Hello, World3!\n', 'Hello, World4!\n', 'Hello, World5!']

In the above code, variable x is a list because the readlines() method returns a list. Since readlines() method returns a list, it can also be iterated with for-loop

Example 2:

fp=open("hello.txt","r")
x=fp.readlines()
for line in x:
    print(line)
fp.close()
Hello, World1!

Hello, World2!

Hello, World3!

Hello, World4!

Hello, World5!

Since each element of x has a newline character("\n") and by default print() function provides a newline character at the end so a new line is printed between each line, if we use print(line, end = "") instead of print(line) then the new line for print() function would not be printed.

Example 3:

fp=open("hello.txt","r")

# printing the first line
x=fp.readlines(14)
print(x)

# printing the next two line
x=fp.readlines(15)
print(x)

# printing the rest lines
x=fp.readlines(-1)
print(x)

fp.close()
['Hello, World1!\n']
['Hello, World2!\n', 'Hello, World3!\n']
['Hello, World4!\n', 'Hello, World5!']
  • In the above code first we have used readlines() method with argument as 14 . As the length of 1st line is 14 so it just has printed the first line . Now the file pointer stands at 1st position of the 2nd line .
  • Then we have used readlines() method with argument as 15 . As the length of second line is 14 so with the 2nd line it has also printed the 3rd line . Now the file pointer stands at 1st position of the 4th line .
  • After that we have used readlines() method with argument as -1 which is the default value . So it has printed all the rest lines of the file .

How to write to a File in Python ?

Python File write() method

With the write method we can write anything in an open file. If we want to write something in a file, we have to open the file in either “w” or “a” access mode. The write method returns an integer whose value is equal to the length of the given string.

Syntax of write() method

file_object.write(string)

Parameters of write() method

string = It is a string which will be written in the file .

Return type of write() method

It returns a integer equal to the length of given string .

Examples of Python File write() method

Example 1:

fp=open("hello1.txt","w")

# writing into the file
x=fp.write("Python is the popular programming language")
print(x)
fp.close()
42

In the above code since the length of "Python is the popular programming language" is 42, so 42 will be printed on the python terminal and the content of “hello1.txt” will be "Python is the popular programming language".

Example 2:

fp=open("hello1.txt","a")

# writing into the file
x=fp.write("Python is the most popular programming language")
print(x)
fp.close()
47

In the above code since the length of "Python is the most popular programming language" is 47, so 47 will be printed on the python terminal and the content of “hello1.txt” will be "Python is the popular programming languagePython is the most popular programming language" . Since the file has been opened in “a” access mode, a new string has been added to the end of the previous string.

Python File writelines() method

Writelines method takes a list object as an argument. With the writelines method we can write many lines together in a file.

Syntax of writelines() method

file_object.writelines(list)

Parameters of writelines() method

list = It is a list whose each element will be written one after another in the given file .

Return type of writelines() method

It returns None .

Examples of Python File writelines() method

Example 1: Write to a file in Python line by line

list1=["hello world1\n","hello world2\n","hello world3"]
fp=open("hello1.txt","w")

# writing multiple lines in hello1.txt
fp.writelines(list1)
fp.close()

In the above code, since the file is opened in “w” access mode, it will delete the old content of “hello1.txt” and rewrite it. Since the program does not have a print statement, it will not print anything on the python terminal.

Example 2:

list1=["hello world1\n","hello world2\n","hello world3"]
fp=open("hello1.txt","a")

# appending multiple lines in hello1.txt
fp.writelines(list1)
fp.close()

In the above code, since the file is opened in “a” access mode, it will write new content at the end of the old content of “hello1.txt”. Since the program does not have a print statement, it will not print anything on the python terminal.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply