Open a File for Reading That Does Not Exist Java

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 information is something we learn 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 pattern of opening and reading files in Python

Here's the official Python documentation on reading and writing from files. Simply before reading that, let'southward dive into the bare minimum that I want you lot to know.

Let'southward only go direct to a code example. Pretend you have a file named example.txt in the current directory. If yous don't, just create one, and then fill it with these lines and relieve it:

          how-do-you-do world and now I say goodbye                  

Here's a short snippet of Python code to open that file and print out its contents to screen – annotation that this Python lawmaking has to be run in the same directory that the example.txt file exists in.

                      myfile            =            open            (            "instance.txt"            )            txt            =            myfile            .            read            ()            impress            (            txt            )            myfile            .            close            ()                  

Did that seem too complicated? Hither'south a less verbose version:

                      myfile            =            open            (            "example.txt"            )            print            (            myfile            .            read            ())            myfile            .            close            ()                  

Here'due south how to read that file, line-by-line, using a for-loop:

                      myfile            =            open up            (            "example.txt"            )            for            line            in            myfile            :            print            (            line            )            myfile            .            shut            ()                  

(Note: If you're getting a FileNotFoundError already – that'south nearly to be expected. Proceed reading!)

However seem as well complicated? Well, there's no getting around the fact that at the programmatic layer, opening a file is singled-out from reading its contents. Not only that, nosotros also have to manually close the file.

Now let's take this step-by-step.

How to open up a file – an interactive exploration

To open up a file, nosotros merely use the open up() method and pass in, every bit the get-go argument, the filename:

                      myfile            =            open            (            "example.txt"            )                  

That seems easy plenty, so permit's jump into some common errors.

How to mess up when opening a file

Here is likely the most common fault you'll get when trying to open a file.

          FileNotFoundError: [Errno 2] No such file or directory: 'SOME_FILENAME'                  

In fact, I've seen students waste material dozens of hours trying to go past this error message, because they don't stop to read it. Then, read it: What does FileNotFoundError mean?

Endeavour putting spaces where the capitalization occurs:

                      File Non Found Error                  

You'll get this error because you lot tried to open a file that simply doesn't exist. Sometimes, information technology's a simple typo, trying to open up() a file named "example.txt" simply accidentally misspelling it equally "exmple.txt".

But more than ofttimes, information technology's because you know a file exists under a given filename, such as "instance.txt" – but how does your Python code know where that file is? Is information technology the "example.txt" that exists in your Downloads binder? Or the ane that might exist in your Documents binder? Or the thousands of other folders on your computer organization?

That's a pretty complicated question. Simply the get-go pace in non wasting your time is that if you e'er come across this fault, finish 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 reckoner, so re-run the script to see if the fault magically fixes itself.

The error FileNotFoundError occurs because y'all either don't know where a file actually is on your computer. Or, even if you lot do, you lot don't know how to tell your Python program where information technology is. Don't try to set up other parts of your code that aren't related to specifying filenames or paths.

How to fix a FileNotFoundError

Here'south a surefire gear up: brand sure the file actually exists.

Let's start from scratch by making an fault. In your arrangement shell (i.eastward. Terminal), change to your Desktop folder:

                      $                        cd            ~/Desktop                  

Now, run ipython:

                      $            ipython                  

And now that you lot're in the interactive Python interpreter, endeavour to open a filename that you know does not exist on your Desktop, and then enjoy the error message:

                      >>>            myfile            =            open up            (            "whateverdude.txt"            )                  
          --------------------------------------------------------------------------- FileNotFoundError                         Traceback (almost contempo call final) <ipython-input-i-4234adaa1c35> in <module>() ----> 1 myfile = open("whateverdude.txt")  FileNotFoundError: [Errno ii] No such file or directory: 'whateverdude.txt'                  

Now manually create the file on your Desktop, using Sublime Text three or whatsoever you lot want. Add together some text to it, and then save it.

          this is my file                  

Wait and see for yourself that this file actually exists in your Desktop folder:

image desktop-whateverdude.png

OK, at present switch back to your interactive Python shell (i.due east. ipython), the ane that you opened after irresolute into the Desktop folder (i.east. cd ~/Desktop). Re-run that open() control, the 1 that resulted in the FileNotFoundError:

                      >>>            myfile            =            open up            (            "whateverdude.txt"            )                  

Hopefully, you shouldn't get an error.

But what is that object that the myfile variable points to? Use the type() method to effigy it out:

                      >>>            blazon            (            myfile            )            _io            .            TextIOWrapper                  

And what is that? The details aren't important, other than to point out that myfile is most definitely not merely a string literal, i.e. str.

Use the Tab autocomplete (i.e. blazon in myfile.) to become a list of existing methods and attributes for the myfile object:

          myfile.buffer          myfile.isatty          myfile.readlines myfile.close           myfile.line_buffering  myfile.seek myfile.closed          myfile.way            myfile.seekable myfile.disassemble          myfile.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 just read() from them. Only let's focus on merely reading for now.

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's in that mystuff variable? Again, utilize the type() part:

                      >>>            blazon            (            mystuff            )            str                  

It's just a string. Which means of form that we can print it out:

                      >>>            print            (            mystuff            )            this            is            my            file                  

Or count the number of characters:

                      >>>            len            (            mystuff            )            15                  

Or print it out in all-caps:

                      >>>            impress            (            mystuff            .            upper            ())            THIS            IS            MY            FILE                  

And that's all there's to reading from a file that has been opened.

At present onto the mistakes.

How to mess up when reading from a file

Here's a very, very common error:

                      >>>            filename            =            "instance.txt"            >>>            filename            .            read            ()                  

The fault output:

          AttributeError                            Traceback (most recent call last) <ipython-input-9-441b57e838ab> in <module>() ----> 1 filename.read()  AttributeError: 'str' object has no aspect 'read'                  

Have careful notation that this is not a FileNotFoundError. It is an AttributeError – which, admittedly, is not very clear – but read the next part:

          'str' object has no attribute 'read'                  

The error message gets to the point: the str object – i.e. a string literal, e.g. something like "hi world" does not take a read attribute.

Revisiting the erroneous code:

                      >>>            filename            =            "example.txt"            >>>            filename            .            read            ()                  

If filename points to "instance.txt", then filename is only a str object.

In other words, a file proper name is non a file object. Hither's a clearer example of errneous lawmaking:

                      >>>            "example.txt"            .            read            ()                  

And to beat the point about the caput:

                      >>>            "howdy globe this is merely a string"            .            read            ()                  

Why is this such a common mistake? Because in 99% of our typical interactions with files, we meet a filename on our Desktop graphical interface and nosotros double-click that filename to open information technology. The graphical interface obfuscates the procedure – and for good reason. Who cares what'south happening as long as my file opens when I double-click it!

Unfortunately, we have to care when trying to read a file programmatically. Opening a file is a discrete operation from reading it.

  • You open a file by passing its filename – due east.1000. example.txt – into the open up() function. The open() function returns a file object.
  • To actually read the contents of a file, you lot phone call that file object's read() method.

Again, here's the lawmaking, in a slightly more than verbose fashion:

                      >>>            myfilename            =            "case.txt"            >>>            myfile            =            open            (            myfilename            )            >>>            mystuff            =            myfile            .            read            ()            >>>            # do something to mystuff, like print it, or whatsoever            >>>            myfile            .            close            ()                  

The file object also has a shut() method, which formally cleans up after the opened file and allows other programs to safely access it. Again, that's a low-level detail that you never call up of in day-to-day calculating. In fact, information technology's something you probably will forget in the programming context, every bit not endmost the file won't automatically break anything (non until we offset doing much more than complicated types of file operations, at to the lowest degree…). Typically, every bit soon as a script finishes, any unclosed files will automatically be closed.

All the same, I like closing the file explicitly – not just 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-by-line

One of the advantages of getting down into the lower-level details of opening and reading from files is that nosotros at present have the power to read files line-by-line, rather than i giant chunk. Over again, to read files equally 1 giant chunk of content, use the read() method:

                      >>>            myfile            =            open            (            "instance.txt"            )            >>>            mystuff            =            myfile            .            read            ()                  

It doesn't seem like such a big deal now, but that's because example.txt probably contains simply a few lines. But when nosotros deal with files that are massive – similar all 3.3 meg records of anybody who has donated more than $200 to a single U.S. presidential entrada commission in 2012 or everyone who has always 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 ane,000,000), information technology's considering most users exercise want to operate on a information file, all at once. However, many interesting data files are just too big for that. Nosotros'll run into those scenarios later on in the quarter.

For at present, here's what reading line-by-line typically looks like:

                      myfile            =            open up            (            "example.txt"            )            for            line            in            myfile            :            print            (            line            )            myfile            .            close            ()                  

Because each line in a textfile has a newline character (which is represented every bit \due north simply is typically "invisible"), invoking the impress() role will create double-spaced output, because print() adds a newline to what it outputs (i.e. recollect back to your original impress("hi world") program).

To get rid of that effect, call the strip() method, which belongs to str objects and removes whitespace characters from the left and correct side of a text cord:

                      myfile            =            open            (            "instance.txt"            )            for            line            in            myfile            :            print            (            line            .            strip            ())            myfile            .            close            ()                  

And of class, yous tin make things loud with the skilful ol' upper() function:

                      myfile            =            open            (            "instance.txt"            )            for            line            in            myfile            :            impress            (            line            .            strip            ())            myfile            .            close            ()                  

That's information technology for now. We oasis't covered how to write to a file (which is a far more dangerous operation) – I salvage that for a separate lesson. Merely information technology'southward enough to know that when dealing with files equally a programmer, we have to exist 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 avert catastrophic mistakes when writing to files.

Python Input and Output Tutorial

At that place are several ways to present the output of a program; data can be printed in a human-readable course, or written to a file for future use. This chapter will discuss some of the possibilities.

ramosopirted.blogspot.com

Source: http://www.compciv.org/guides/python/fileio/open-and-read-text-files/

0 Response to "Open a File for Reading That Does Not Exist Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel