Python How to Read a File Once

File Handling in Python

Last updated on July 27, 2020


So far in this grade, nosotros have been using variables to shop data. The problem with this arroyo is that as soon equally program ends our data is lost. Ane mode to store the data permanently is to put information technology in a file. This chapter discusses how we can store data in the file every bit well every bit read data from the file.

In Python, File Handling consists of following three steps:

  1. Open up the file.
  2. Procedure file i.e perform read or write operation.
  3. Close the file.

Types of File #

In that location are ii types of files:

  1. Text Files
  2. Binary Files

A file whose contents tin be viewed using a text editor is called a text file. A text file is simply a sequence of ASCII or Unicode characters. Python programs, HTML source lawmaking are some of the example of text files.

A binary file stores the data in the same way as as stored in the memory. The mp3 files, prototype files, word documents are some of the examples of binary files. You tin't read a binary file using a text editor.

In this lesson nosotros will discuss how to work with both types of files.

Let'southward start.

Opening a File #

Before you perform whatever functioning on a file, you must the open it. Python provides a function called fopen() to open a file. Information technology'southward syntax is:

                        fileobject            =            open            (            filename            ,            mode            )          

The filename is the name or path of the file.

The mode is a string which specifies the blazon operation you lot want to perform on the file (i.e read, write, append, etc).The following table lists different modes available to yous.

Way Description
"r" Opens the file for reading. If the file doesn't already exists y'all will get FileNotFoundError error.
"west" Opens the file for writing. In this style, if file specified doesn't exists, information technology will be created. If the file exists, then information technology's data is destroyed.
"a" Opens the file in append mode. If the file doesn't exists this mode volition create the file. If the file already exists then it appends new data to the stop of the file rather than destroying information as "w" mode does.

We can besides specify the blazon of file (i.e text file or binary file.) we want to work with in fashion string by appending 't' for text files and 'b' for binary files. But since text manner is default mode, it is mostly omitted while opening files in text mode.

On success, open() returns a file object which is associated with the filename specified while calling information technology.

Hither are some examples of how to open a file:

Example one:

                        f            =            open            (            "employees.txt"            ,            "rt"            )          

This statement opens the text file employees.txt for reading. Since text fashion is default, the above argument tin can too be written equally:

                        f            =            open            (            "employees.txt"            ,            "r"            )          

Case 2:

                        f            =            open up            (            "teams.txt"            ,            "due west"            )          

This statement opens the text file in write mode.

Example 3:

                        f            =            open            (            "teams.dat"            ,            "wb"            )          

This statement opens the binary file in write way.

Instance iv:

                        f            =            open            (            "teams.dat"            ,            "ab"            )          

This statement opens the binary file in suspend mode.

Instead of using relative file paths we can also use absolute file paths. For example:

                        f            =            open up            (            "/home/tom/documents/README.doctor"            ,            "w"            )          

This statements opens the text file README.dr. that is in /home/tom/documents/ directory in write mode.

In Windows, retrieve to escape backslashes while using absolute path names, Otherwise, you will become an error. For example:

                        f            =            open up            (            "C:            \\            Users            \\            tom            \\            documents            \\            README.md"            ,            "west"            )          

We can as well use something called "raw cord" by specifying r character in front of the string as follows:

                        f            =            open            (            r            "C:\Users\tom\documents\README.md"            ,            "w"            )          

The r character causes the Python to care for every grapheme in string as literal characters.

Closing the File #

Once we are done working with the file or we want to open the file in another style, we should close the file using shut() method of the file object as follows:

Closing a file releases valuable system resources. In case you forgot to close the file, Python will automatically shut the file when program ends or file object is no longer referenced in the program. Even so, if your program is large and you are reading or writing multiple files that can take significant amount of resource on the organisation. If you go along opening new files carelessly, yous could run out of resources. And so exist a good programmer and close the file as soon every bit you lot are done with it.

TextIOWrapper class #

The file object returned by open() office is an object of type _io.TextIOWrapper. The class _io.TextIOWrapper provides methods and attributes which helps u.s.a. to read or write data to and from the file. The following table lists some commonly used methods of _io.TextIOWrapper class.

Method Clarification
read([num]) Reads the specified number of characters from the file and returns them equally string. If num is omitted then it reads the entire file.
readline() Reads a unmarried line and returns it as a string.
readlines() Reads the content of a file line by line and returns them equally a list of strings.
write(str) Writes the string argument to the file and returns the number of characters written to the file.
seek(offset, origin) Moves the file pointer to the given offset from the origin.
tell() Returns the electric current position of the file pointer.
close() Closes the file

Writing Data to the Text File #

The following plan demonstrates how to write data to the the file:

python101/Chapter-18/writing_to_file.py

                                            f                      =                      open                      (                      "readme.md"                      ,                      "w"                      )                      f                      .                      write                      (                      "Get-go Line                      \n                      "                      )                      f                      .                      write                      (                      "2d Line                      \northward                      "                      )                      f                      .                      write                      (                      "Tertiary Line                      \north                      "                      )                      f                      .                      close                      ()                    

In line i, we are using open() method to open up the text file in write mode. If the readme.md file doesn't exists, the open() method will create the file. If the file already exists, then information technology's information will be overwritten. Run the programme and then open readme.medico file. Information technology should look like this:

python101/Chapter-18/readme.md

                      Offset Line Second Line 3rd Line                    

Let'southward take a shut wait at how write() method writes data to the file.

All read and write operations in a file begins at file pointer. What is file arrow ? A file pointer is simply a marker which keeps rail of the number of bytes read or written in a file. This arrow automatically moves after every read or write operation.

When a file is opened the file pointer points at the beginning of the file. The write() part begins writing at the electric current file position and then increments the file arrow. For example, the following figure shows the position of file pointer after each write performance.

Note that dissimilar print() function, write() method practise non print newline character (\due north) at the end of string automatically. We tin can also utilise impress() office to write data to the file. Let's take a closer expect at the signature of the print() using the assist() function.

                      1  2  3  4  v  6  seven  8  9 10 11 12 13 14 15
                                            >>>                      >>>                      help                      (                      print                      )                      Help                      on                      congenital                      -                      in                      function                      print                      in                      module                      builtins                      :                      impress                      (                      ...                      )                      print                      (                      value                      ,                      ...                      ,                      sep                      =                      ' '                      ,                      end                      =                      '                      \northward                      '                      ,                      file                      =                      sys                      .                      stdout                      ,                      flush                      =                      Faux                      )                      Prints                      the                      values                      to                      a                      stream                      ,                      or                      to                      sys                      .                      stdout                      by                      default                      .                      Optional                      keyword                      arguments                      :                      file                      :                      a                      file                      -                      similar                      object                      (                      stream                      );                      defaults                      to                      the                      current                      sys                      .                      stdout                      .                      sep                      :                      string                      inserted                      between                      values                      ,                      default                      a                      space                      .                      end                      :                      cord                      appended                      after                      the                      last                      value                      ,                      default                      a                      newline                      .                      flush                      :                      whether                      to                      forcibly                      affluent                      the                      stream                      .                      >>>                    

Notice the fourth parameter in the part signature i.east file. By default, file points to the standard output means information technology volition print data to the screen. To output data to a file just specify the file object. The following program uses print() office instead of write() to write data to the file.

python101/Affiliate-18/writing_data_using_print_function.py

                                            f                      =                      open                      (                      "readme.md"                      ,                      "westward"                      )                      impress                      (                      "First Line"                      ,                      file                      =                      f                      )                      print                      (                      "Second Line"                      ,                      file                      =                      f                      )                      print                      (                      "Third Line"                      ,                      file                      =                      f                      )                      f                      .                      shut                      ()                    

This program produces the same output equally before, the only deviation is that, in this case the newline graphic symbol (\n) is automatically added by the print() role.

Reading Information from a Text file #

To read a file you must open it in "r" mode. In addition to that, you lot should besides ensure that the file you want to read already exists because in "r" mode the open() function throws FileNotFoundError error if its unable to find a file.

To test whether a file exists or not, we can apply isfile() function from the os.path module. The syntax of isfile() is:

If file found at the given path isfile() returns Truthful. Otherwise False. The following shell session demonstrates working of isfile() office.

                                            >>>                      >>>                      import                      bone                      >>>                      >>>                      bone                      .                      path                      .                      isfile                      (                      "/home/q/python101/Chapter-18/readme.doc"                      )                      # file exists                      True                      >>>                      >>>                      bone                      .                      path                      .                      isfile                      (                      "/home/q/python101/Chapter-eighteen/alphabetize.html"                      )                      # file doesn't exists                      False                      >>>                    

The post-obit programs demonstrates how to read a file using read(), readline() and readlines() office.

Example 1: Reading data at once using the read() method.

python101/Affiliate-xviii/read_method_demo.py

                                            f                      =                      open                      (                      "readme.doctor"                      ,                      "r"                      )                      print                      (                      f                      .                      read                      ())                      # read all content at once                      f                      .                      close                      ()                    

Output:

                      Outset Line Second Line 3rd Line                    

Example 2: Reading information in chunks using the read() method.

python101/Affiliate-xviii/reading_in_chunks.py

                                            f                      =                      open                      (                      "readme.md"                      ,                      "r"                      )                      print                      (                      "First chunk:"                      ,                      f                      .                      read                      (                      4                      ),                      stop                      =                      "                      \due north\n                      "                      )                      # read the outset iv characters                      print                      (                      "2nd chunk:"                      ,                      f                      .                      read                      (                      ten                      ),                      end                      =                      "                      \due north\n                      "                      )                      # read the next ten grapheme                      print                      (                      "3rd clamper:"                      ,                      f                      .                      read                      (),                      terminate                      =                      "                      \n\n                      "                      )                      # read the remaining characters                                            f                      .                      close                      ()                    

Output:

                      First chunk: Firs  2d chunk: t Line Sec  Third chunk: ond Line Third Line                    

When the file is open in read mode the file pointer points at the beginning of the file.

After reading first iv characters, file arrow is at t.

Afterwards reading the next 10 characters, file arrow is at grapheme o.

The third call to read() reads the remaining characters in the file and returns them as a string. At this point, the file position pointer points at the terminate of the file. Consequently, any subsequent calls to read() method returns an empty cord.

Example 3: Using readline() to read data from a file.

python101/Affiliate-18/readline_method_demo.py

                      i  2  3  4  five  6  7  8  9 10 11 12 thirteen 14 15 16 17 xviii
                                            f                      =                      open                      (                      "readme.medico"                      ,                      "r"                      )                      # read outset line                      print                      (                      "Ist line:"                      ,                      f                      .                      readline                      ())                      # read the fist two characters in the second line                      impress                      (                      "The first two characters in the second line:"                      ,                      f                      .                      read                      (                      2                      ),                      finish                      =                      "                      \northward\northward                      "                      )                      # read the remaining characters int the 2d line                      print                      (                      "Remaining characters in the 2d line:"                      ,                      f                      .                      readline                      ())                      # read the next line                      print                      (                      "3rd line:"                      ,                      f                      .                      readline                      ())                      # finish of the file reached, so readline returns an empty string ""                      print                      (                      "After end of file :"                      ,                      f                      .                      readline                      ())                      f                      .                      close                      ()                    

Output:

                      Ist line: Commencement Line  The commencement 2 characters in the 2nd line: Se  Remaining characters in the 2d line: cond Line  3rd line: Tertiary Line  Afterwards end of file :                    

Equally usual when file is opened, the file arrow points at the offset of the file.

The first call to readline() method moves the file arrow to the get-go of side by side line.

The read() function then reads two characters from the file which moves the file pointer to the character c.

In line 10, the readline() is called once more just this fourth dimension it starts reading from the character c to the end of the line (including the newline grapheme).

In line thirteen, readline() is called once again, to read the last line. At this point, file position pointer is at the end of the file. That'due south why readline() telephone call in line 16 returns an empty cord ("").

Example 4: Using readlines() to read data from a file.

python101/Chapter-18/readlines_method_demo.py

                                            f                      =                      open                      (                      "readme.md"                      ,                      "r"                      )                      # read all the line as render and them as a list of strings                      impress                      (                      f                      .                      readlines                      ())                      f                      .                      close                      ()                    

Output:

            ['Start Line\n', '2d Line\n', 'Tertiary Line\north']          

Reading Large Files #

The read() and readlines() methods piece of work bang-up with small-scale files. But what if your file has thousands or millions of lines in it? In such cases using read() or readlines() may event in memory hogs. A improve approach would be to apply loops and read file data in small chunks. For case:

python101/Chapter-eighteen/reading_large_file_demo1.py

                      ane  2  three  4  5  6  seven  8  9 10 11 12 13 14 fifteen 16
                                            f                      =                      open                      (                      "readme.md"                      ,                      "r"                      )                      clamper                      =                      10                      # specify clamper size                      data                      =                      ""                      # keep looping until at that place is information in the file                      while                      True                      :                      data                      =                      f                      .                      read                      (                      chunk                      )                      print                      (                      data                      ,                      cease                      =                      ""                      )                      # if stop of file is reached, break out of the while loop                      if                      information                      ==                      ""                      :                      intermission                      f                      .                      close                      ()                    

Output:

                      First Line Second Line Third Line                    

Here we are using an infinite loop to iterate over the contents of the file. As soon as the end of file is reached, the read() method returns an empty cord (""), if condition in line 12, evaluates to true and break statement causes the loop to finish.

Python also allows u.s.a. to apply for loop to loop through the file data using file object as follows:

python101/Chapter-18/reading_large_files_using_for_loop.py

                                            f                      =                      open                      (                      "readme.md"                      ,                      "r"                      )                      for                      line                      in                      f                      :                      impress                      (                      line                      ,                      end                      =                      ""                      )                      f                      .                      close                      ()                    

Output:

                      First Line 2d Line Third Line                    

Appending Data to the Text File #

We can use "a" fashion to suspend information to end of the file. The following program demonstrates how to append data to the end of the file.

python101/Affiliate-eighteen/append_data.py

                      1  2  three  4  v  6  7  8  9 ten xi 12 xiii 14 15 16 17 18 xix
                                            f                      =                      open                      (                      "readme.md"                      ,                      "a"                      )                      print                      (                      "Appending data to the stop of the file ..."                      )                      f                      .                      write                      (                      "4th Line                      \n                      "                      )                      f                      .                      write                      (                      "Fifth Line                      \n                      "                      )                      impress                      (                      "Done!"                      )                      f                      .                      close                      ()                      ## open the file over again                      print                      (                      "                      \n                      Opening the file again to read the data ...                      \n                      "                      )                      f                      =                      open                      (                      "readme.md"                      ,                      "r"                      )                      for                      line                      in                      f                      :                      print                      (                      line                      ,                      end                      =                      ""                      )                      f                      .                      shut                      ()                    

Output:

                      Appending data to the stop of the file ... Done!  Opening the file over again to read the data ...  First Line 2nd Line 3rd Line Fourth Line 5th Line                    

Working with files using the with statement #

Python too provides a squeamish shortcut for file handling using the with statement. The following is the general form of the with statement when used with files.

                                            with                      open                      (                      filename                      ,                      fashion                      )                      every bit                      file_object                      :                      # torso of with statement                      # perform the file operations here                    

The best thing nearly this shortcut is that it automatically closes the file without requiring any work on your part. The statements inside the torso of the with statement must be equally indented otherwise y'all volition get an fault. The scope of file_object variable is merely limited to the body of the with statement. If y'all try to call read() or write() method on information technology outside the block you will get an error.

The following examples show how we tin employ the with statement to read and write data to and from the file.

Example one: Reading information line by line using for loop.

python101/Chapter-18/with_statement.py

                                            with                      open                      (                      "readme.doctor"                      ,                      "r"                      )                      as                      f                      :                      for                      line                      in                      f                      :                      impress                      (                      line                      ,                      end                      =                      ""                      )                    

Output:

                      First Line 2nd Line 3rd Line Fourth Line Fifth Line                    

Example 2: Reading all information at once using read() method.

python101/Affiliate-18/with_statement2.py

                                            with                      open                      (                      "readme.md"                      ,                      "r"                      )                      as                      f                      :                      print                      (                      f                      .                      read                      ())                    

Output:

                      Beginning Line 2d Line Third Line Quaternary Line 5th Line                    

Example iii: Reading a large file in pocket-sized chunks.

python101/Chapter-18/with_statement3.py

                      one  ii  iii  4  5  6  vii  viii  9 ten eleven 12
                                            with                      open                      (                      "readme.md"                      ,                      "r"                      )                      as                      f                      :                      chunk                      =                      10                      # specify chunk size                      information                      =                      ""                      # keep looping until there is information in the file                      while                      Truthful                      :                      information                      =                      f                      .                      read                      (                      chunk                      )                      print                      (                      data                      ,                      finish                      =                      ""                      )                      # if end of file is reached, break out of the while loop                      if                      information                      ==                      ""                      :                      suspension                    

Output:

                      Kickoff Line 2d Line Tertiary Line Fourth Line Fifth Line                    

Case 4: Writing data to a file using the write() method

python101/Affiliate-18/with_statement4.py

                                            with                      open                      (                      "random.txt"                      ,                      "west"                      )                      equally                      f                      :                      f                      .                      write                      (                      "Ane D                      \n                      "                      )                      f                      .                      write                      (                      "2 D                      \n                      "                      )                      f                      .                      write                      (                      "THREE D                      \n                      "                      )                      f                      .                      write                      (                      "FOUR D                      \n                      "                      )                    

Reading and Writing Binary Data #

The post-obit program copies binary data from a source file (source.jpg) to a target file (dest.jpg).

python101/Chapter-eighteen/reading_and_writing_binary_data.py

                      1  2  3  4  five  vi  7  eight  ix 10 11 12 13
                                            f_source                      =                      open up                      (                      "source.jpg"                      ,                      "rb"                      )                      f_dest                      =                      open                      (                      "dest.jpg"                      ,                      "wb"                      )                      char_count                      =                      0                      for                      line                      in                      f_source                      :                      char_count                      +=                      len                      (                      line                      )                      f_dest                      .                      write                      (                      line                      )                      print                      (                      char_count                      ,                      "characters copied successfully"                      )                      f_source                      .                      close                      ()                      f_dest                      .                      shut                      ()                    

Output:

            2115658 characters copied successfully          

Run the program and information technology should create dest.jpg file in the aforementioned directory as source.jpg.



Ezoic

wortmanexcurce.blogspot.com

Source: https://overiq.com/python-101/file-handling-in-python/

0 Response to "Python How to Read a File Once"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel