C++ Open File Read Encoded Decoded Message

On this folio: open(), file.read(), file.readlines(), file.write(), file.writelines().

Before proceeding, make sure you sympathise the concepts of file path and CWD. If yous run into problems, visit the Common Pitfalls section at the bottom of this page.

Opening and Closing a "File Object"

As seen in Tutorials #12 and #13, file IO (input/output) operations are done through a file information object. Information technology typically proceeds as follows:
  1. Create a file object using the open() role. Along with the file proper name, specify:
    • 'r' for reading in an existing file (default; can be dropped),
    • 'west' for creating a new file for writing,
    • 'a' for appending new content to an existing file.
  2. Do something with the file object (reading, writing).
  3. Shut the file object by calling the .close() method on the file object.
Below, myfile is the file data object we're creating for reading. 'alice.txt' is a pre-existing text file in the aforementioned directory equally the foo.py script. After the file content is read in, .shut() is called on myfile, closing the file object.
myfile = open('alice.txt',              'r')       myfile.close()                                    foo.py            
Below, myfile is opened for writing. In the 2d instance, the 'a' switch makes certain that the new content is tacked on at the end of the existing text file. Had you used 'w' instead, the original file would take been overwritten.
myfile = open('results.txt',              'w')     myfile.close()                        myfile = open('results.txt',              'a')     myfile.shut()                                    foo.py            
There is one more than slice of crucial information: encoding. Some files may have to be read every bit a detail encoding type, and sometimes yous need to write out a file in a specific encoding arrangement. For such cases, the open() statement should include an encoding spcification, with the encoding='30' switch:
myfile = open('alice.txt',              encoding='utf-8'              )        myfile = open('results.txt',              'w',              encoding='utf-eight'              )                 foo.py            
Mostly, you volition need 'utf-8' (8-bit Unicode), 'utf-16' (xvi-bit Unicode), or 'utf-32' (32-bit), but it may exist something different, especially if you are dealing with a strange language text. Here is a full list of encodings.

Reading from a File

OK, nosotros know how to open and close a file object. Only what are the actual commands for reading? There are multiple methods.

Kickoff off,

.read() reads in the entire text content of the file equally a unmarried cord. Below, the file is read into a variable named marytxt, which ends up existence a string-type object. Download mary-short.txt and try out yourself.
                      >>>                      f = open('mary-brusk.txt')                      >>>                      marytxt = f.read()                                   >>>                      f.close()                      >>>                      marytxt                      'Mary had a trivial lamb,\nHis fleece was white as snowfall,\nAnd everywhere that Mary  went,\nThe lamb was certain to get.\northward'                      >>>                      type(marytxt)                                        <blazon 'str'>                      >>>                      len(marytxt)                                         110                      >>>                      print(marytxt[0])                      M                    
Next, .readlines() reads in the entire text content of the file as a list of lines, each terminating with a line break. Below, yous can see marylines is a list of strings, where each string is a line from mary-short.txt.
                      >>>                      f = open('mary-short.txt')                      >>>                      marylines = f.readlines()                            >>>                      f.shut()                      >>>                      marylines                      ['Mary had a niggling lamb,\northward', 'His fleece was white as snow,\northward', 'And everywhere  that Mary went,\n', 'The lamb was sure to go.\due north']                      >>>                      type(marylines)                                      <type 'listing'>                      >>>                      len(marylines)                                       iv                      >>>                      impress(marylines[0])                      Mary had a little lamb,                                          
Lastly, rather than loading the entire file content into retentivity, y'all tin can iterate through the file object line past line using the for ... in loop. This method is more than memory-efficient and therefore recommended when dealing with a very large file. Below, bible-kjv.txt is opened, and any line containing smite is printed out. Download bible-kjv.txt and try out yourself.
f = open up('bible-kjv.txt')      for line in f:                     if              'smite'              in line:          print(line,)                  f.close()              foo.py            

Writing to a File

Writing methods also come in a pair: .write() and .writelines(). Like the corresponding reading methods, .write() handles a single string, while .writelines() handles a list of strings.

Below,

.write() writes a single string each time to the designated output file:
                      >>>                      fout = open('hullo.txt',                      'w')                      >>>                      fout.write('Hello, world!\north')                                      >>>                      fout.write('My proper noun is Homer.\due north')                      >>>                      fout.write("What a beautiful day we're having.\north")                      >>>                      fout.close()                    
This time, we have tobuy, a list of strings, which .writelines() writes out at once:
                      >>>                      tobuy = ['milk\n',                      'butter\n',                      'coffee beans\n',                      'arugula\n']                      >>>                      fout = open('grocerylist.txt',                      'due west')                      >>>                      fout.writelines(tobuy)                                            >>>                      fout.close()                    
Notation that all strings in the examples have the line pause '\due north' at the finish. Without information technology, all strings volition exist printed out on the same line, which is what was happening in Tutorial xiii. Dissimilar the print statement which prints out a cord on its own new line, writing methods will not tack on a newline graphic symbol -- you must recall to supply '\n' if you wish a string to occupy its ain line.

Common Pitfalls

File I/O is notoriously fraught with stumbling blocks for outset programmers. Beneath are the nearly common ones.

"No such file or directory" error

                      >>>                      f = open up('mary-brusque.txt')                      Traceback (most recent call terminal):   File "", line one, in                                                      IOError: [Errno ane] No such file or directory: 'mary-curt.txt'                                                                  
You are getting this fault because Python failed to locate the file for reading. Make certain you are supplying the correct file path and name. Read first File Path and CWD. Also, refer to this, this and this FAQ.

Issues with encoding

                      >>>                      f = open('mary-curt.txt')                          >>>                      marytxt = f.read()                      Traceback (most recent call last):   File "<pyshell#xiv>", line i, in <module>     marytxt = f.read()   File "C:\Programme Files (x86)\Python35-32\lib\encodings\cp1252.py", line 23, in decode     return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 36593: character  maps to <undefined>                    
"UnicodeDecodeError" ways you lot take a file encoding issue. Each estimator has its own system-wide default encoding, and the file you are trying to open is encoded in something dissimilar, most likely some version of Unicode. If this happens, you lot should specify the encoding using the encoding='xxx' switch while opening the file. If you lot are not sure which encoding to use, try 'utf-8', 'utf-sixteen', and 'utf-32'.

Unabridged file content can be read in only ONCE per opening

                      >>>                      f = open('mary-short.txt')                      >>>                      marytxt = f.read()                                 >>>                      marylines = f.readlines()                          >>>                      f.close()                      >>>                      len(marytxt)                      110                      >>>                      len(marylines)                           0                    
Both .read() and .readlines() come up with the concept of a cursor. After either command is executed, the cursor moves to the terminate of the file, leaving nil more to read in. Therefore, once a file content has been read in, another endeavor to read from the file object will produce an empty information object. If for some reason you lot must read the file content again, you must shut and re-open the file.

Only the string type can be written

                      >>>                      pi = iii.141592                      >>>                      fout = open('math.txt',                      'due west')                      >>>                      fout.write("Pi'southward value is ")                      >>>                      fout.write(pi)                                      Traceback (most recent phone call last):   File "", line ane, in                                                      TypeError: expected a character buffer object                                                                    >>>                      fout.write(str(pi))                                >>>                                          
Writing methods only works with strings: .write() takes a single string, and .writelines() takes a list which contains strings merely. Non-string type information must be first coerced into the string type past using the str() part.

Your output file is empty

This happens to everyone: you write something out, open up upward the file to view, simply to find it empty. In other times, the file content may exist incomplete. Curious, isn't it? Well, the cause is simple: Yous FORGOT .shut(). Writing out happens in buffers; flushing out the last writing buffer does not happen until y'all close your file object. ALWAYS Recall TO Shut YOUR FILE OBJECT.

(Windows) Line breaks do non testify upwards
If you open up your text file in Notepad app in Windows and see everything in one line, don't be alarmed. Open the same text file in Wordpad or, fifty-fifty better, Notepad++, and you will see that the line breaks are at that place after all. See this FAQ for details.

johnsonalittly.blogspot.com

Source: https://sites.pitt.edu/~naraehan/python3/reading_writing_methods.html

0 Response to "C++ Open File Read Encoded Decoded Message"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel