How to Read and Write Text Files in Python

Reading and writing files in Python will require you to have some basic knowledge about the programme. It is extremely important learn how to read and write files that exist inside and outside of the application itself. Python is a very clever programme that allows you to modify certain types of files using certain tools that are integral part of the application. So what are you waiting for? Learn the tricks of the trade and start editing files in Python that provide a simple mechanism for accessing and modifying files.

Instructions

  • 1

    Before doing anything else you will need to make sure that you have some basic IT and computer skills. Without knowing how to operate a computer you will not be able to perform this task. Once you have made up your mind, consider deciding on usage policy. Before opening any file in Python, you will need to know whether you want to read or write from the file. It is recommended not to open the file in read-write mode when you are only required to write to it. This will help you keep the file from accidental writes that you should not be doing.

  • 2

    Next, find out if you need to use binary mode or ASCII. Consider using the ASCII mode if you only need to read text from the file. Use the binary mode if you are required to read binary data. This action will help you open the file in the mode your operating system is compatible with.

  • 3

    Now make the mode string in the programme. The first character displayed is either write or read mode. Use “b” character at the end of the string if you plan on reading binary date. The “r” character must be used at the end of the mode string for reading files in ASCII mode. Use the function f = open ("/filename/goes/here", "r") to open the file.

  • 4

    Use the read method of a selected file for reading binary data from a binary data file. It is possible to read arbitrary numbers from a file using the command given below.

    # Read 16 bytes from the file
    buf = f.read(16)

  • 5

    You must seek a certain point in the file where you want to read the text from. Use the method given below to seek to a certain point in the file before reading.

    # Seek to the 100th byte
    f.seek(100)

    # Seek to 10 bytes from the current byte
    f.seek(10, 1)

  • 6

    When a file is opened in write mode, choose if you need to write binary data or ASCII to it. Use the method below to perform this task.

    f.write("This is some text")

Leave a Reply

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


+ five = 9