Python Write to File

In this article, we will discuss python write to file, opening a file, closing, and appending with code examples.

Python Write to File Introduction

Python has methods for creating, writing, and reading files. In Python, there are two types of files that may be handled: text files and binary files (written in binary language, 0s, and 1s).

  • Text files: Each line of text in this type of file is concluded with a unique character known as EOL (End of Line), which is the new line character (‘\n’) in Python by default.
  • Binary files: There is no line terminator in this file, and the data is saved after being converted into machine-readable binary language.

File Access Modes

The access modes control the kind of activities that can be performed on the opened file. It describes how the file will be utilized once it has been opened. These modes additionally specify where the FileHandle is in the file. Python has six different access modes.

  1. Read Only (‘r’): This allows you to read a text file. The handle is located at the start of the file. If the file does not exist, and an I/O error is generate. This is also the default method for opening files.
  2. Read and Write (‘r+’): This allows you to read and write to a file. The handle is located at the start of the file. If the file does not exist, and an I/O error is generate.
  3. Write Only (‘w’): This allows you to open the file for writing. The data in an existing file is truncate and overwritten. The handle is located at the start of the file. If the file does not exist, it is create.
  4. Write and Read (‘w+’): This allows you to read and write to a file. The data in an existing file is truncate and overwritten. The handle is located at the start of the file.
  5. Only Append (‘a’): Open the file for writing. If the file does not already exist, it is create. The handle is at the very end of the file. The new data will be add at the end, following the old data.
  6. Append and Read (‘a+’): This allows you to read and write to a file. If the file does not already exist, it is create. The handle is at the very end of the file. The new data will be add at the end, following the old data.

Opening a File

The open() function is use to do this. This function does not need the import of any modules.

File_object = open(r"File_Name","Access_Mode")

The file must be in the same directory as the Python program file; otherwise, the entire location of the file must be written in place of the filename.

Note: The r is add before the filename string to prevent it from being interprete as a special character. If there is \temp in the file address, for example, \t is interprete as the tab character and an error of incorrect address is produce. The r marks the string as raw, indicating that it contains no special characters. If the file is in the same directory and the address is not being inserted, the r can be disregarded.


file1 = open("SofthuntFile1.txt","a")
file2 = open(r"D:\Python\Text\SofthuntFile2.txt","w+")

Here, file1 is create as an object for SofthuntFile1 and file2 as an object for SofthuntFile2.

Closing a File

The close() function closes the file and frees the memory space used by it. It is use when a file is no longer require or when it is to be open in a different file mode.

File_object.close()
file1 = open("SofhuntFile1.txt","a")
file1.close()

Python Write to File

There are two ways to write in a file.

write(): Inserts the string str1 in a single line in the text file.

File_object.write(str1)

writelines(): For a list of string elements, each string is insert into the text file. Used to insert multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3] 

Note: ‘\n’ is treat as a special character of two bytes.

# Opening a file
file1 = open('SofthuntFile1.txt', 'w')
multiple_string = ["This is Mango \n", "This is Apple \n", "This is Banana \n"]
single_string = "Hi\n"

# Writing a string to file
file1.write(single_string)

# Writing multiple strings at a time
file1.writelines(multiple_string)

# Closing file
file1.close()

# Checking if the data is written to file or not
file1 = open('SofthuntFile1.txt', 'r')
print(file1.read())
file1.close()

Output:

Hello
This is Mango
This is Apple
This is Banana

Reading from a file

There are three ways to read data from a text file.

read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.

File_object.read([n])

readline(): Reads a line of the file and returns in form of a string. For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.

File_object.readline([n])

readlines(): Reads all the lines and returns them as each line a string element in a list.

File_object.readlines()

Note: ‘\n’ is treat as a special character of two bytes

# write data in a file.
file1 = open("SofthuntFile1.txt","w")
multiple_string = ["This is Mango \n","This is Apple \n","This is Banana \n"]

# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(multiple_string)
file1.close() #to change file access modes

file1 = open("SofthuntFile1.txt","r+")

print("Output of Read function is ")
print(file1.read())
print()

# seek(n) takes the file handle to the nth
 bite from the beginning.
file1.seek(0)

print( "Output of Readline function is ")
print(file1.readline())
print()

file1.seek(0)

# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")
print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

Output:

Output of Read function is 
Hello 
This is Mango 
This is Apple
This is Banana 

Output of Readline function is 
Hello 


Output of Read(9) function is 
Hello 
Th

Output of Readline(9) function is 
Hello 

Output of Readlines function is 
['Hello \n', 'This is Mango \n', 'This is Apple \n', 'This is Banana \n']

Appending to a file

The handle is at the end of the file when the file is open in append mode. The new data will be add at the end, following the old data. Let’s look at an example to show how Python Write to File mode differs from the append mode.


# Append vs write mode
file1 = open("SofthuntFile1.txt", "w")
multiple_string = ["This is Mango \n", "This is Apple \n", "This is Banana \n"]
file1.writelines(multiple_string)
file1.close()

# Append-adds at last
file1 = open("SofthuntFile1.txt", "a") # append mode
file1.write("This is Strawberry\n")
file1.close()

file1 = open("SofthuntFile1.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()

# Write-Overwrites
file1 = open("SofthuntFile1.txt", "w") # write mode
file1.write("This is Peach \n")
file1.close()

file1 = open("SofthuntFile1.txt", "r")
print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()

Output:

Output of Readlines after appending
This is Mango
This is Apple
This is Banana
This is Strawberry


Output of Readlines after writing
This is Peach

Conclusion of Python Write to File

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Unit Testing with Python unittest

Leave a Comment