Reading and writing to text files in Python



Python provides built-in functions for creating, writing, and reading files. There are two types of files that can be processed in Python, plain text files and binaries (written in binary, 0 and 1).

  • Text files: in In this type of file, each line of text is terminated with a special EOL (end of line) character, which is the default newline character (& # 39; / n & # 39;) in python.
  • Binaries: there is no line separator in this file type, and the data is preserved after converting it to machine-readable binary.

In this article, we will focus on opening, closing, reading and writing data to text file.

File access modes

Access modes determine the type of possible operations in an open file. This refers to how the file will be used after opening it. These modes also determine the location of the file descriptor in the file. A file descriptor is like a cursor that defines where data should be read from or written to the file. Python has 6 access modes.

  1. Read only (& # 39; r & # 39;): open a text file for reading. The descriptor is located at the beginning of the file. If the file does not exist, an I / O error occurs. This is also the default mode in which the file is opened.
  2. Read and Write (& # 39; r + & # 39;): open the file for reading and writing. The descriptor is located at the beginning of the file. Throws an I / O error if the file does not exist.
  3. Write only (& # 39; w & # 39;): open file for writing. For an existing file, data is truncated and overwritten. The descriptor is located at the beginning of the file. Creates a file if the file does not exist.
  4. Write and Read (& # 39; w + & # 39;) : Open the file for reading and writing. For an existing file, data is truncated and overwritten. The descriptor is located at the beginning of the file.
  5. Append Only (& # 39; a & # 39;) : Open the file for writing. The file is created if it doesn`t exist. The descriptor is located at the end of the file. The data to be written will be inserted at the end, after the existing data.
  6. Add and Read (& # 39; a + & # 39;): open the file for reading and writing. The file is created if it doesn`t exist. The descriptor is located at the end of the file. The data being written will be inserted at the end, after the existing data.

Opening a file

This is done using the open () function. This function does not require a module import.

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

The file must exist in the same directory as the python program file, in Otherwise, the full address of the file must be written in place of the file name. 
Note: r is placed before the filename to prevent characters in the filename string from being treated as special characters. For example, if a file contains / temp, then / t is treated as a tab character and an invalid address error occurs. R makes the string unprocessed, that is, it says that the string has no special characters. The r character can be ignored if the file is in the same directory and the URL is not located.

# Open the function to open the file "MyFile1.txt"
# (same directory) in add mode and

file1 = open ( "MyFile.txt" , "a" )

 
# save your link in the file1 variable
# and "MyFile2.txt" in D: / text in file2

file2 = open (r "D: TextMyFile2 .txt " , " w + " )

Here file1 is created as an object for MyFile1 and file2 as an object for MyFile2

Closing the file

The close () function closes the file and frees the memory space allocated by this file. It is used when the file is no longer needed, or when it needs to be opened in a different file mode.

File_object.close ()

# Open and close the file" MyFile.txt "
# for the object name file1.

file1 = open ( "MyFile.txt" , "a" )

file1.close ()

Write to file

There are two ways to write to file.

  1. write (): inserts line str1 on one line in a text file.
     File_object.write (str1) 
  2. writelines (): for a list of string items, each line is inserted into a text file. Used to insert multiple lines at the same time.
     File_object.writelines (L) for L = [str1, str2, str3] 

Read from file

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

  1. read (): returns the bytes read as a string. Reads n bytes, if n is not specified, reads the entire file.
     File_object.read ([n]) 
  2. readline (): reads a line from a file and returns as a string. For the specified n, reads at most n bytes. However, it does not read more than one line, even if n is longer than the line length.
     File_object.readline ([n]) 
  3. readlines (): reads all lines and returns them as each line as a line item in the list.
     File_object.readlines () 

Note: & # 39; / n & # 39; treated as a two-byte special character

# Program for showing different reading methods and
# write data to a file.

file1 = open ( "myfile.txt" , "w" )

L = [ "This is Delhi" , "This is Paris" , "This is London"

 
# / n is placed to indicate EOL (End strings)

file1.write ( "Hello" )

file1.writelines (L)

file1.close () # change file access mode

 

file1 = open ( "myfile.txt" , "r +"

 

print "Output of Read function is"

print file1. read ()

print

 
# seek (n) translates file descriptor to nth # bite from the beginning.

file1.seek ( 0

  

print "Output of Readline function is"

print file1.readline ()

print

 

file1.seek ( 0 )

 
# Show the 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:

 Ou tput of Read function is Hello This is Delhi This is Paris This is London 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`, `This is Delhi`, `This is Paris`, `This is London`] 

Attach to file

# Python program for illustration
# Add against write mode

file1 = open ( " myfile.txt " , " w " )

L = [ "This is Delhi" , "This is Paris" , " This is London "

file1.close ()

 
# Add-add finally

file1 = open ( " myfile.txt " , " a " ) # append mode

file1.write ( " Today " )

file1.close ()

 

file1 = open ( "myfile.txt"  , "r" )

print "Output of Readlines after appending"

print file1.readlines ()

print
file1.close ()

  
# Write-overwrite

file1 = open ( "myfile.txt" , " w " ) # write mode

file1 .write ( "Tomorrow" )

file1.close ()

 

< p> file1 = open ( "myfile.txt" , "r" )

print "Output of Readlines after writing"

print file1.readlines ()

print
file1.close ()

Output:

 Output of Readlines after appending [`This is Delhi`, `This is Paris`, `This is London`, `Today`] Output of Readlines after writing [`Tomorrow`] 

Related article: