Python Tutorial 19 : How to read/write a text file?

In Python, we purely use the Open function to open or create a text file. We on’t need to import any external library as it is an built-in function.

Following is the syntax for the open function

open( < File Name>,<Mode>)

File Mode in Python

ModeDescription
‘r’open for reading (default)
‘w’This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
‘x’Creates a new file. If file already exists, the operation fails.
‘a’Open file in append mode.
If file does not exist, it creates a new file.
‘t’This is the default mode. It opens in text mode.
‘b’This opens in binary mode.
‘+’This will open a file for reading and writing (updating)

 

How to Read a Text File

Through out this tutorial, you may have to use windows command prompt.

Therefore, you may consider to refer to following tutorials for instruction regarding to Command Prompt:

Read a Text File Line-By-Line

Suppose we want to read the following text file.

Text file to read by PythonThis text file is currently stored in following path

“C:\ACapturer\Python”

Following program reads the file line-by-line.

Read text File in Python

To run the application, simply open Command Prompt

C:\>cd\acapturer\Python

C:\ACapturer\Python>python read_file.py testing.txt

Read text File in Python - Result

 

Let’s explain what is this program doing.

  1. This program starts from line 15″import sys”Import the sys library into the program. This allow the program to accept argument from command prompt
  2. read the first argument from command prompt[vtftable cols=”{0}0:fff2cc;{/}”]
    name = sys.argv[1]
    [/vtftable]
  3. Pass the input result into the readfile procedure[vtftable cols=”{0}0:fff2cc;{/}”]
    readfile(name)
    [/vtftable]
  4. In the readfile procedure, it firstly use the open function to open the file into an object variable “infile”[vtftable cols=”{0}0:fff2cc;{/}”]
    infile = open(filepath)
    [/vtftable]
  5. Print each line in the file using a “For Loop”[vtftable cols=”{0}0:fff2cc;{/}”]
    for line in infile:
    print(line, end = ”)
    [/vtftable]
  6. Close the input file[vtftable cols=”{0}0:fff2cc;{/}”]
    infile.close
    [/vtftable]

 

Read a Text File as all-in-one

 

The program above can be replaced as follow:

Read text File All-in-one in Python

Let’s explain what is this program doing.

  1. This program starts from line 15″import sys”Import the sys library into the program. This allow the program to accept argument from command prompt
  2. read the first argument from command prompt
    [vtftable cols=”{0}0:fff2cc;{/}”]
    name = sys.argv[1]
    [/vtftable]
  3. Pass the input result into the readfile procedure
    [vtftable cols=”{0}0:fff2cc;{/}”]
    readfile(name)
    [/vtftable]In the readfile procedure
  4. It firstly use the open function to open the file into an object variable “infile”[vtftable cols=”{0}0:fff2cc;{/}”]
    infile = open(filepath)
    [/vtftable]
  5. Check if the file is ready to read[vtftable cols=”{0}0:fff2cc;{/}”]
    if infile.mode ==’r’
    [/vtftable]
  6. Read the file into a variable “contents”[vtftable cols=”{0}0:fff2cc;{/}”]
    contents = infile.read()
    print(contents)
    [/vtftable]
  7. Close the input file[vtftable cols=”{0}0:fff2cc;{/}”]
    infile.close
    [/vtftable]

 

How to Create a Text File

Suppose we want to create a file called “Testing 2.txt” where stores user input until user typed enter twice.

Following is the program:Create new text file in Python

 

Following is the test result

Create new text file in Python - input

Let’s explain what is this program doing.

  1. This program Import the sys library into the program . This allow the program to accept argument from command prompt[vtftable cols=”{0}0:fff2cc;{/}”]
    import sys
    [/vtftable]
  2. read the first argument from command prompt[vtftable cols=”{0}0:fff2cc;{/}”]
    filename= sys.argv[1]
    [/vtftable]
  3. Accept the first line from your input[vtftable cols=”{0}0:fff2cc;{/}”]
    line = input(“”)
    [/vtftable]
  4. Check if the first line is is not blank[vtftable cols=”{0}0:fff2cc;{/}”]
    if line != “”:
    [/vtftable]
  5. Open the new file for writing[vtftable cols=”{0}0:fff2cc;{/}”]
    outfile = open(filename,”w”)
    [/vtftable]
  6. Loop while the input line is not blank[vtftable cols=”{0}0:fff2cc;{/}”]
    while line !=””:
    [/vtftable]
  7. Write the line into the output file and then accept a new line. Repeat the loop until user entered a blank line[vtftable cols=”{0}0:fff2cc;{/}”]
    outfile.write(line + ‘\n’)
    line = input(“”)
    [/vtftable]
  8. Close the output file
  9. [vtftable cols=”{0}0:fff2cc;{/}”]
    outfile.close
    [/vtftable]

 

Let’s use the “read_file.py” program to read the file

Create new text file in Python - Result

How to Append Data to a File

Suppose we want to update the file “test2.txt”.

Following is the program:

Append text to existing file in Python

 

Following is the test result

Append text to existing file in Python - Result

 

In the result, we firstly review the current content of the test2.txt file using the “read_file” program, then we use this new program to add an extra line “See you tomorrow!” and review the content of the “test2.txt” again.

Let’s explain what is this program doing.

  1. This program Import the sys library into the program . This allow the program to accept argument from command prompt[vtftable cols=”{0}0:fff2cc;{/}”]
    import sys
    [/vtftable]
  2. read the first argument from command prompt[vtftable cols=”{0}0:fff2cc;{/}”]
    filename= sys.argv[1]
    [/vtftable]
  3. Accept the first line from your input[vtftable cols=”{0}0:fff2cc;{/}”]
    line = input(“”)
    [/vtftable]
  4. Check if the first line is is not blank[vtftable cols=”{0}0:fff2cc;{/}”]
    if line != “”:
    [/vtftable]
  5. Open the new file for append[vtftable cols=”{0}0:fff2cc;{/}”]
    outfile = open(filename,”a”)
    [/vtftable]
  6. Loop while the input line is not blank[vtftable cols=”{0}0:fff2cc;{/}”]
    while line !=””:
    [/vtftable]
  7. Write the line into the output file and then accept a new line. Repeat the loop until user entered a blank line[vtftable cols=”{0}0:fff2cc;{/}”]
    outfile.write(line + ‘\n’)
    line = input(“”)
    [/vtftable]
  8. Close the output file
  9. [vtftable cols=”{0}0:fff2cc;{/}”]
    outfile.close
    [/vtftable]

 

Summary

  • Python allows you to read, write and delete files
  • Use the function open(“filename”,”w”) to create a file.
  • To append data to an existing file use the command open(“Filename”, “a“)
  • Use the read function to read the ENTIRE contents of a file
  • Use the readlines function to read the content of the file one by one.

Leave a Comment