Writing to text file in Python

Python has built-in file creation, capabilities for writing, and reading capabilities. There is no need to import an external library to read and write files in Python. For generating, writing, and reading files, the built-in functions in Python are sufficient to handle it out of the box.

In Python, two sorts of files can 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 terminated with a unique character called EOL (End of Line), which is the new line character (‘n’) in Python. There is no terminator for a line in a binary file, and the data is saved after being converted into machine-readable binary language.

Files

Files are locations identified on a disk where associated data is responsibly stored. The latter is used to keep data in non-volatile memory for a long time, e.g., hard disk. We use files for future data usage by permanently saving them because Random Access Memory (RAM) is volatile (it loses its contents when the machine is turned off).

We must first open a file before reading from or writing to it. Later, it needs to be closed to release the file’s resources when we’re finished. As a result, a file operation in Python is performed in the following order:

  • Create a new file
  • You can either read or write (operate)
  • Close the document.

We’ll look at how to open, close, read, and write data in a text file in this tutorial.

File Methods in Python

With the file object, you may use a variety of methods. Some of these will be highly utilized in the examples we will tackle in this article. Here’s a list of all the methods in text mode, along with a brief description:

  • close() -Closes a file that has been opened.
  • If the file is already closed, it has no effect.
  • detach() -Returns the underlying binary buffer after separating it from the TextIOBase.
  • fileno()- returns the file’s integer number (file descriptor).
  • flush() – Flushes the file stream’s write buffer.
  • isatty() -Is a function that returns a value. If the file stream is interactive, this value is true.
  • read(n) – Reads a maximum of n characters from a file. If the value is negative or None, it reads until the end of the file.
  • readable() – Returns the number of characters in a string. If the file stream is read, this value is true.
  • readline(n=-1) – Reads one line from the file and returns it. If n is supplied, it reads in at most n bytes.
  • readlines(n=-1) – Reads a file and returns a list of lines. If n is given, it reads in at most n bytes/characters.
  • seek(offset,from=SEEK SET) – Changes the file position in reference to from to offset bytes (start, current, end).
  • Seekable() – If the file stream enables random access, seekable() returns True.
  • tell() – Returns an integer representing the file’s object’s current position.
  • truncate(size=None)- resizes the file stream to the specified size in bytes. If no size is supplied, it will resize to the current location.
  • writable() – Returns a value that is writable. If the file stream is written to, this value is true.
  • write(s) – Returns the number of characters written after writing the string s to the file.
  • writelines(lines) – Creates a file with a list of lines.

Modes of File Access

The access modes determine the kind of operations performed on the opened file. It specifies how the file is utilized after it has been opened. These modes likewise define the File Handle’s placement in the file. A filehandle functions similarly to a cursor, indicating where data should be read or written in the file.

Python has six different access modes as follows:

Read Only (‘r’)

Open a text file for reading with the Read-Only (‘r’) option. The handle is at the beginning of the document. If the file does not exist, an I/O error is raised. It is also the default mode for opening files.

Read and Write (‘r+’)

Allows you to read and write to a file. The handle is at the beginning of the document. If the file does not exist, an I/O error is thrown.

Write Only (‘w’)

Allows you to write to a file. The data in an existing file is truncated and overwritten. The handle is at the beginning of the document. On the occasion that the file does not exist, it is created.

Write and Read (‘w+’)

Allows you to read and write to a file. Data is shortened and overwritten for existing files. The handle is at the beginning of the document.

Append Only (‘a’)

Allows you to write to a file. In case the needed file does not exist, it is created. The file’s handle is located at the very end. After the existing data, the data that is being written will be added at the end.

Append and Read (‘a+’)

To read and write in the file, double-click it. If the file does not exist, it is created. The file’s handle is located at the very end. After the existing data, the data that is being written will be added at the end.

How to open a File

The open() function is used to accomplish this. This function does not necessitate the import of any modules.

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

Otherwise, the complete location of the file is written in place of the filename if the file is not in the same directory as the python program file.

The r before filename prevents the characters in the filename string from being regarded as special characters. The r indicates that the string is raw, meaning no special characters. If the file is in the same directory as the address, the r is disregarded. For example, if there is a \temp character in the file address, the \t is regarded as a tab character, and an invalid address error is raised.

# The function open is responsible for  opening the given file "TestFileOne.txt"
# use append mode if the file is in the same directory
file_one = open("test_file.txt","a")

# store its reference in the variable file1
# and "test_file_two.txt" in C:\Text in the second text file
file_two = open(r"C:\Text\test_file_two.txt","w+")

Here, file_one is generated as a TestFileOne object, while file_two is produced as a TestFileTwo object.

Closing a file

The close() function terminates a file and releases the memory space it has taken up. It’s utilized when the file isn’t needed anymore or when it has to be accessed in a different file mode.

The file will remain open until you use the close() function to close it. This operation is performed after writing the data into the file since it frees up the memory space that the file has obtained. Otherwise, an unhandled exception may occur. The ‘with’ statement is responsible for closing the file after completing the writing process. We don’t have to define a close method explicitly every time.

# File_object.close()
# Opening and Closing a file "TestFileOne.txt"
# for object name file_one.
file_one = open("TestFileOne.txt","a")
file_one.close()

Creating a file

A file is written in one of two ways.

write()

Writes the string str1 to the text file in a single line.

File_object.write(str1)

writelines()

It inserts each string into a text file from a list of string elements. Multiple strings can be inserted at once using this method.

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

Reading information from a file

A text file is read in three different ways.

read()

Returns a string containing the read bytes. Reads n bytes or the entire file if no n is given.

File_object.read([n])

readline()

It reads a single line from a file and returns it as a string. Reads at most n bytes for the provided n. If n is greater than the line length, it does not read more than one line.

File_object.readline([n])

readlines()

Reads all the lines and returns them as a list of string elements, one for each line.

File_object.readlines()

Note that ‘\n’ is handled as a two-byte unique character.

# Program showing diverse approaches to reading and writing data in a file.
file_one = open("test_file.txt","w")
L = ["This is Manchester \n","This is Liverpool \n","This is London \n"]

#  The placement of \n indicates End of Line
file_one.write("Hello \n")
file_one.writelines(L)
file_one.close() #to change file access modes

file_one = open("test_file.txt","r+")

print("Read function Output ")
print(file_one.read())
print()

# seek(n) takes the filehandle to the nth
# bite from the beginning.
file_one.seek(0)

print( "Readline function Output ")
print(file_one.readline())
print()

file_one.seek(0)

# illustrating the difference between read and readline
print("Output of Read(9) function is ")
print(file_one.read(9))
print()

file_one.seek(0)

print("Readline(9) function Output ")
print(file_one.readline(9))

file_one.seek(0)
# readlines function
print("Readlines function Output ")
print(file_one.readlines())
print()
file_one.close()

How to append to a file

# program illustrating how to append vs the write mode
file_one = open("test_file.txt","w")
L = ["This is Manchester \n","This is Liverpool \n","This is London \n"]
file_one.writelines(L)
file_one.close()

# adding at the last position is called append
file_one = open("test_file.txt","a")#append mode
file_one.write("Today \n")
file_one.close()

file_one = open("test_file.txt","r")
print("Readlines  output  post appending")
print(file_one.readlines())
print()
file_one.close()

# Write-Overwrites
file_one = open("test_file.txt","w")#write mode
file_one.write("Tomorrow \n")
file_one.close()

file_one = open("test_file.txt","r")
print("Readlines  output post writing")
print(file_one.readlines())
print()
file_one.close()

Example 1: Using the write() function, write a line to a text file

Let’s use the write() method to write a line into a text file. The ‘with’ statement is necessary to close the file after completing the writing process. We don’t need to define a closure method explicitly.

# Program for writing text  to a designated file using the function, write()
with  open("test_file.txt", "w") as file:
	content = "Hello, Codeunderscored is your to go to place on matters Python !! \n"
	file.write(content)
	file.close()


# Program for reading the whole file given an absolute path using the read() function
with open("D:/TEXT/test_file.txt", "r") as file:
	content = file.read()
	print(content)
	file.close()

Example : Using the write() function to append a line to a text file

If you want to attach the line to an existing text file, you must open it in append mode and then use the write() function, as illustrated below.

# Program for appending new  information to a text file using the function, write()
with  open("test_file.txt", "a") as file:
	content = "Add new Codeunderscored content at the end \n"
	file.write(content)
	file.close()


# Program for reading the whole file when provided with the absolute path using the read() function
with open("D:/TEXT/test_file.txt", "r") as file:
	content = file.read()
	print(content)
	file.close()

Example : Using the writelines() function to create a list and save it to a file

Let’s use the writelines() method to write multiple lines into a text file. The writelines() method takes an iterable object like a list, set, or tuple as input. Let’s look at how to write a list to a file in Python using the example below.

Writelines’ syntax ()

file.writelines(list)

Parameters

list – This is the list of texts or byte objects to be added. It could be a list, tuple, string set, or something else entirely.

# Program for writing many lines to a given text file using the function writelines()
with open("test_file.txt", "w") as file:
    content = ["Hello\n", "Codeunderscored is your to go to place on matters Python !!\n", "Cheers \n" ]
    file.writelines(content)
    file.close()

# Program for reading the whole file given an absolute path using the read() function
with open("D:/TEXT/test_file.txt", "r") as file:
    content = file.read()
    print(content)
    file.close()

Example: Using the writelines() function in appending many lines to a text file

If you want to add several lines to an existing text file, you must open it in append mode and then use the writelines() function, as illustrated below.

# Program for appending to a given text file by using the function - writelines()
with open("test_file.txt", "a") as file:
    content = ["How to append the content\n", "Python\n" ]
    file.writelines(content)
    file.close()

# Program for reading the whole file given an absolute path and using the function- read()
with open("C:/TEXT/test_file.txt", "r") as file:
    content = file.read()
    print(content)
    file.close()

Conclusion

Using Python’s built-in functions, file operations, such as creating, reading, and writing files, make handling work very easy. Regular text files and binary files are the two types of files that Python can handle. We’ve looked at how to write material into text files in Python in this article.

In a standard text file, every line of text in the text file is finished with the unique character “End of Line” (EOL). Python is the new line character (‘\n’) by default. On the other hand, no line is terminated in a binary file, and the data is kept once it is transformed to machine binary code.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *