Start Reading at the Beginning of a File Again in C
Opening files and reading from files
How to opening files and read from files and avoid annoying mistakes when reading files
Summary
Opening files and reading their data is something we acquire how to do with a simple double-click in our earliest interactions with computers. However, at the programmatic layer, things are substantially more complicated…
The basic blueprint of opening and reading files in Python
Here's the official Python documentation on reading and writing from files. But before reading that, let's swoop into the bare minimum that I desire you to know.
Let'southward just go straight to a code instance. Pretend you have a file named case.txt in the current directory. If you don't, only create one, and so fill up information technology with these lines and salvage it:
how-do-you-do earth and at present I say goodbye
Here'south a short snippet of Python code to open that file and print out its contents to screen – notation that this Python code has to exist run in the same directory that the example.txt
file exists in.
myfile = open ( "case.txt" ) txt = myfile . read () impress ( txt ) myfile . shut ()
Did that seem too complicated? Here's a less verbose version:
myfile = open up ( "example.txt" ) print ( myfile . read ()) myfile . close ()
Here's how to read that file, line-by-line, using a for-loop:
myfile = open ( "instance.txt" ) for line in myfile : impress ( line ) myfile . close ()
(Note: If you're getting a FileNotFoundError already – that's almost to be expected. Continue reading!)
Nonetheless seem besides complicated? Well, there'due south no getting around the fact that at the programmatic layer, opening a file is distinct from reading its contents. Non only that, we as well have to manually shut the file.
Now allow's take this step-by-step.
How to open a file – an interactive exploration
To open a file, nosotros simply use the open()
method and laissez passer in, every bit the get-go argument, the filename:
myfile = open ( "example.txt" )
That seems easy plenty, so let's leap into some common errors.
How to mess upward when opening a file
Here is likely the well-nigh common fault you'll become when trying to open a file.
FileNotFoundError: [Errno two] No such file or directory: 'SOME_FILENAME'
In fact, I've seen students waste dozens of hours trying to get by this error message, because they don't terminate to read it. So, read information technology: What does FileNotFoundError
mean?
Try putting spaces where the capitalization occurs:
File Not Institute Fault
Yous'll get this error because you tried to open a file that simply doesn't exist. Sometimes, it's a simple typo, trying to open()
a file named "case.txt"
but accidentally misspelling it every bit "exmple.txt"
.
But more often, it's because you know a file exists under a given filename, such equally "example.txt"
– but how does your Python code know where that file is? Is it the "example.txt"
that exists in your Downloads binder? Or the i that might exist in your Documents folder? Or the thousands of other folders on your reckoner system?
That'southward a pretty complicated question. Just the start pace in not wasting your fourth dimension is that if you ever run into this mistake, cease whatsoever else you are doing. Don't tweak your convoluted for-loop. Don't effort to install a new Python library. Don't restart your computer, then re-run the script to meet if the fault magically fixes itself.
The mistake FileNotFoundError
occurs considering you either don't know where a file actually is on your computer. Or, even if yous do, you lot don't know how to tell your Python programme where it is. Don't endeavour to fix other parts of your code that aren't related to specifying filenames or paths.
How to ready a FileNotFoundError
Here's a surefire fix: make sure the file actually exists.
Let's start from scratch by making an error. In your system vanquish (i.e. Final), modify to your Desktop binder:
$ cd ~/Desktop
At present, run ipython:
$ ipython
And now that you're in the interactive Python interpreter, try to open up a filename that you know does not be on your Desktop, and then bask the error message:
>>> myfile = open ( "whateverdude.txt" )
--------------------------------------------------------------------------- FileNotFoundError Traceback (most contempo call last) <ipython-input-i-4234adaa1c35> in <module>() ----> 1 myfile = open("whateverdude.txt") FileNotFoundError: [Errno 2] No such file or directory: 'whateverdude.txt'
Now manually create the file on your Desktop, using Sublime Text iii or whatever you desire. Add together some text to it, then save it.
this is my file
Look and see for yourself that this file actually exists in your Desktop binder:
OK, at present switch back to your interactive Python shell (i.e. ipython), the 1 that you opened after irresolute into the Desktop folder (i.e. cd ~/Desktop
). Re-run that open()
command, the 1 that resulted in the FileNotFoundError:
>>> myfile = open ( "whateverdude.txt" )
Hopefully, y'all shouldn't become an error.
But what is that object that the myfile
variable points to? Employ the blazon()
method to figure it out:
>>> type ( myfile ) _io . TextIOWrapper
And what is that? The details aren't important, other than to point out that myfile
is most definitely not just a string literal, i.eastward. str
.
Use the Tab autocomplete (i.due east. blazon in myfile.
) to become a listing of existing methods and attributes for the myfile
object:
myfile.buffer myfile.isatty myfile.readlines myfile.close myfile.line_buffering myfile.seek myfile.airtight myfile.manner myfile.seekable myfile.detach myfile.proper name myfile.tell myfile.encoding myfile.newlines myfile.truncate myfile.errors myfile.read myfile.writable myfile.fileno myfile.readable myfile.write myfile.flush myfile.readline myfile.writelines
Well, we can do a lot more with files than only read()
from them. Just allow's focus on only reading for at present.
How to read from a file – an interactive exploration
Assuming the myfile
variable points to some kind of file object, this is how you read from it:
>>> mystuff = myfile . read ()
What'southward in that mystuff
variable? Again, use the type()
role:
>>> type ( mystuff ) str
It'south simply a string. Which means of course that we can print information technology out:
>>> print ( mystuff ) this is my file
Or count the number of characters:
>>> len ( mystuff ) 15
Or print it out in all-caps:
>>> print ( mystuff . upper ()) THIS IS MY FILE
And that'south all there's to reading from a file that has been opened.
Now onto the mistakes.
How to mess upward when reading from a file
Here's a very, very common mistake:
>>> filename = "case.txt" >>> filename . read ()
The error output:
AttributeError Traceback (virtually contempo call last) <ipython-input-9-441b57e838ab> in <module>() ----> one filename.read() AttributeError: 'str' object has no attribute 'read'
Take conscientious note that this is not a FileNotFoundError. It is an AttributeError – which, admittedly, is non very clear – but read the next role:
'str' object has no attribute 'read'
The error message gets to the bespeak: the str
object – i.e. a string literal, e.g. something like "hi world"
does not have a read
attribute.
Revisiting the erroneous code:
>>> filename = "case.txt" >>> filename . read ()
If filename
points to "example.txt", and so filename
is but a str
object.
In other words, a file name is non a file object. Hither's a clearer instance of errneous code:
>>> "example.txt" . read ()
And to beat the point almost the head:
>>> "hello globe this is just a string" . read ()
Why is this such a mutual mistake? Because in 99% of our typical interactions with files, we see a filename on our Desktop graphical interface and we double-click that filename to open up it. The graphical interface obfuscates the process – and for proficient reason. Who cares what's happening equally long equally my file opens when I double-click it!
Unfortunately, nosotros have to care when trying to read a file programmatically. Opening a file is a detached operation from reading it.
- Y'all open up a file by passing its filename – east.one thousand.
example.txt
– into theopen up()
function. Theopen()
function returns a file object. - To really read the contents of a file, you lot call that file object'southward read() method.
Again, here'due south the lawmaking, in a slightly more than verbose fashion:
>>> myfilename = "example.txt" >>> myfile = open ( myfilename ) >>> mystuff = myfile . read () >>> # practise something to mystuff, like print information technology, or whatever >>> myfile . close ()
The file object also has a close()
method, which formally cleans up subsequently the opened file and allows other programs to safely access it. Again, that'south a depression-level detail that you never recollect of in day-to-day computing. In fact, it'southward something y'all probably will forget in the programming context, equally not closing the file won't automatically break anything (not until nosotros commencement doing much more complicated types of file operations, at least…). Typically, as presently as a script finishes, whatsoever unclosed files volition automatically be closed.
Even so, I like closing the file explicitly – not simply to be on the safe side – but information technology helps to reinforce the concept of that file object.
How to read from a file – line-past-line
Ane of the advantages of getting downward into the lower-level details of opening and reading from files is that we now have the ability to read files line-past-line, rather than 1 giant chunk. Again, to read files every bit ane behemothic chunk of content, use the read()
method:
>>> myfile = open ( "case.txt" ) >>> mystuff = myfile . read ()
It doesn't seem similar such a big deal now, but that's because instance.txt
probably contains just a few lines. But when we deal with files that are massive – like all three.three 1000000 records of everyone who has donated more $200 to a single U.S. presidential campaign commission in 2012 or everyone who has ever visited the White Business firm – opening and reading the file all at once is noticeably slower. And it may even crash your computer.
If y'all've wondered why spreadsheet software, such as Excel, has a limit of rows (roughly 1,000,000), it's because well-nigh users do desire to operate on a data file, all at once. However, many interesting data files are just too big for that. We'll run into those scenarios subsequently in the quarter.
For now, here'due south what reading line-by-line typically looks like:
myfile = open up ( "case.txt" ) for line in myfile : print ( line ) myfile . close ()
Considering each line in a textfile has a newline character (which is represented as \due north
simply is typically "invisible"), invoking the print() function will create double-spaced output, because print() adds a newline to what it outputs (i.e. recollect back to your original print("hello earth")
program).
To become rid of that effect, phone call the strip()
method, which belongs to str
objects and removes whitespace characters from the left and right side of a text cord:
myfile = open up ( "example.txt" ) for line in myfile : print ( line . strip ()) myfile . close ()
And of grade, you tin brand things loud with the good ol' upper()
function:
myfile = open ( "example.txt" ) for line in myfile : print ( line . strip ()) myfile . close ()
That'south it for now. Nosotros haven't covered how to write to a file (which is a far more than unsafe functioning) – I save that for a separate lesson. Only it's enough to know that when dealing with files as a developer, we have to be much more explicit and specific in the steps.
References and Related Readings
Opening files and writing to files
How to open files and write to files and avoid catastrophic mistakes when writing to files.
Python Input and Output Tutorial
There are several means to present the output of a programme; data tin can exist printed in a human-readable form, or written to a file for future use. This chapter volition discuss some of the possibilities.
Source: http://www.compciv.org/guides/python/fileio/open-and-read-text-files/
0 Response to "Start Reading at the Beginning of a File Again in C"
Post a Comment