Writing to a file 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 ends 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 it is converted to machine-readable binary.

Note. To learn more about processing files, Access mode

  • Opening a file
  • Closing a file
  • Writing to file

  • Access mode

    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. Different access modes for reading the file —

    1. Write only (& # 39; w & # 39;): open the 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.
    2. 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.
    3. 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 being written will be inserted at the end, after the existing data.

    Note. To learn more about the access mode, click here .

    Opening file

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

    Syntax :

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

    The file must exist in the same directory as the python program file, otherwise the full file address must be written in place of the file name.

    Note: r is placed before the file name so that characters in the file name string are not 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 read mode and

    file1 = open ( "MyFile.txt" , "w"

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

    file2 = open (r "D: TextMyFile2.tx t " , " w + "

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

    Closing a file

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

    Syntax :

     File_object.close () 

    # Open and close the file & quot; MyFile.txt & quot;
    # for the object name file1 .

    file1 = open ( "MyFile.txt" , " w "

    file1.close () 

    Writing to file

    There are two ways to write to a file.

    1. write (): inserts the string str1 on one line in a text file.
       File_object.write (str1) 
    2. writelines (): for a list of inline 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] 

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

    Example :

    # Python program to demonstrate
    # write to file

    # Opening the file

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

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

    s = " Hello "

    # Writing line to file
    file1.write (s)

    # Writing multiple lines
    # on time
    file1.writelines (L)

    # Closing file
    file1.close ()

    # Data validation
    # written to file or not

    file1 < code class = "keyword"> = open ( `myfile.txt ` , ` r` )

    print (file1.read ())

    file1.close ()


     Hello This is Delhi This is Paris This is London 

    Attaching to a file

    When a file is opened in append mode, the descriptor is located at the end file. The data to be written will be inserted at the end, after the existing data. Let`s take a look at the example below to clarify the difference between write mode and add mode.

    # Python program for illustration
    # Add against write mode

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

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

    file1.writelines (L)
    file1.close ()

    # Add- add finally

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

    file1.write ( " Today " )

    file1.close ()


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

    print ( "Output of Readlines after appending" )

    print (file1.read ())

    print ()

    file1.close ()

    # Overwrite

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

    file1.write ( "Tomorrow" )

    file1.close ()


    file1 = op en ( "myfile.txt" , "r" )

    print ( "Output of Readlines after writing" )

    print (file1.read ())

    print ()

    file1.close ()


     Output of Readlines after appending This is Delhi This is Paris This is London Today Output of Readlines after writing Tomorrow 

    With statement

    The with statement in Python is used to handle exceptions to make your code cleaner and much more readable. This makes it easier to manage shared resources such as file streams. Unlike the implementations described above, when used with an operator, there is no need to call file.close () . The with statement itself ensures that resources are acquired and released correctly.

    Syntax :

     with open filename as file: 

    # Program for showing different ways
    # write data to a file using the with statement


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

    # Write to file

    with open ( "myfile.txt" , "w" ) as file1:

    # Writing data to file

    file1.write ( "Hello" )

    file1.writelines (L)

    # Read from file

    with open ( " myfile.txt " , "r +" ) as file1:

    # Read from file

      print (file1.read ())

    Exit :

     Hello This is Delhi This is Paris This is London 

    Note: to learn more about the statement, click here .