Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 30, 2022 03:19 pm GMT

Python Files and Exceptions

Working with files makes your programs more relevant and usable, also it makes your programs quickly analyze lots of data.

Learning to work with files and save data will make your programs easier for people to use. Users will be able to choose what data to enter and when to enter it. People can run your program, do some work, and then close the program and pick up where they left off later. Learning to handle exceptions will help you deal with situations in which files dont exist and deal with other problems that can cause your programs to crash. This will make your programs more robust when they encounter bad data, whether it comes from innocent mistakes or from malicious attempts to break your programs. With these skills, youll make your programs more applicable, usable, and stable.

Reading from a File

An incredible amount of data is available in text files. Text files can contain weather data, traffic data, socioeconomic data, literary works, and more. Reading from a file is particularly useful in data analysis applications, but its also applicable to any situation in which you want to analyze or modify information stored in a file. For example, you can write a program that reads in the contents of a text file and rewrites the file with formatting that allows a browser to display it.

When you want to work with the information in a text file, the first step is to read the file into memory. You can read the entire contents of a file, or you can work through the file one line at a time.

Reading an Entire File

To begin, we need a file with a few lines of text in it. Lets start with a file that contains pi to 30 decimal places, with 10 decimal places per line, consider we have a text file (pi_digits. txt) in the same directory of your program:

3.1415926535  8979323846  2643383279

Heres a program that opens this file, reads it, and prints the contents of the file to the screen:

with open('pi_digits.txt') as file_object:    contents = file_object.read()print(contents)

The first line of this program with open('pi_digits.txt') as file_object: has a lot going on. Lets start by looking at the open() function. To do any work with a file, even just printing its contents, you first need to open the file to access it. The open() function needs one argument: the name of the file you want to open. Python looks for this file in the directory where the program thats currently being executed is stored.

Here, open('pi_digits.txt') returns an object representing pi_digits.txt. Python assigns this object to file_object, which well work with later in the program.

The keyword with closes the file once access to it is no longer needed. Notice how we call open() in this program but not close(). You could open and close the file by calling open() and close(), but if a bug in your program prevents the close() method from being executed, the file may never close. This may seem trivial, but improperly closed files can cause data to be lost or corrupted. And if you call close() too early in your program, youll find yourself trying to work with a closed file (a file you cant access), which leads to more errors. Its not always easy to know exactly when you should close a file, but with the structure shown here, Python will figure that out for you. All you have to do is open the file and work with it as desired, trusting that Python will close it automatically when the with block finishes execution.

Once we have a file object representing pi_digits.txt, we use the read() method in the second line of our program contents = file_object.read() to read the entire contents of the file and store it as one long string in contents. When we print the value of contents, we get the entire text file back.

If you find a blank line appears at the end of your output that's because read() returns an empty string when it reaches the end of the file; this empty string shows up as a blank line. If you want to remove the extra blank line, you can use rstrip() in the call to print().

print(contents.rstrip())

File Paths

When you pass a simple filename like pi_digits.txt to the open() function, Python looks in the directory where the file thats currently being executed (that is, your . py program file) is stored.

Sometimes, depending on how you organize your work, the file you want to open wont be in the same directory as your program file. For example, you might store your program files in a folder called python_work; inside python_work, you might have another folder called text_files to distinguish your program files from the text files theyre manipulating. Even though text_files is in python_work, just passing open()*the name of a file in *text_files wont work, because Python will only look in python_work and stop there; it wont go on and look in text_files.

To get Python to open files from a directory other than the one where your program file is stored, you need to provide a file path, which tells Python to look in a specific location on your system.

Because text_files is inside python_work, you could use a relative file path to open a file from text_files. A relative file path tells Python to look for a given location relative to the directory where the currently running program file is stored. For example, youd write:

with open('text_files/filename.txt') as file_object:

This line tells Python to look for the desired . txt file in the folder text_files and assumes that text_files is located inside python_work.

Please note that, Windows systems use a backslash ( \ ) instead of a forward slash ( / ) when displaying file paths, but you can still use forward slashes in your code.

You can also tell Python exactly where the file is on your computer regardless of where the program thats being executed is stored. This is called an absolute file path. You use an absolute path if a relative path doesnt work. For instance, if youve put text_files in some folder other than python_worksay, a folder called other_filesthen just passing open() the path 'text_files/filename.txt' wont work because Python will only look for that location inside python_work. Youll need to write out a full path to clarify where you want Python to look.

Absolute paths are usually longer than relative paths, so its helpful to assign them to a variable and then pass that variable to open():

file_path = '/home/ahmed/other_files/text_files/filename.txt'with open(file_path) as file_object:

Using absolute paths, you can read files from any location on your system. For now its easiest to store files in the same directory as your program files or in a folder such as text_files within the directory that stores your program files.

Please note that, if you try to use backslashes in a file path, youll get an error because the backslash is used to escape characters in strings. For example, in the path C:\patho\file.txt, the sequence is interpreted as a tab. If you need to use backslashes, you can escape each one in the path, like this: C:\\path\o\\file.txt.

Reading Line by Line

When youre reading a file, youll often want to examine each line of the file. You might be looking for certain information in the file, or you might want to modify the text in the file in some way. For example, you might want to read through a file of weather data and work with any line that includes the word sunny in the description of that days weather. In a news report, you might look for any line with the tag <headline> and rewrite that line with a specific kind of formatting.

You can use a for loop on the file object to examine each line from a file one at a time:

file_name = 'pi_digits.txt'with open(file_name) as file_object:    for line in file_object:        print(line)
3.1415926535  8979323846  2643383279

At file_name = 'pi_digits.txt' we assign the name of the file were reading from to the variable filename. This is a common convention when working with files. Because the variable filename doesnt represent the actual fileits just a string telling Python where to find the fileyou can easily swap out 'pi_digits. txt' for the name of another file you want to work with.

After we call open(), an object representing the file and its contents is assigned to the variable
file_object. We again use the with syntax to let Python open and close the file properly. To examine the files contents, we work through each line in the file by looping over the file object.

When we print each line, we find even more blank lines. These blank lines appear because an invisible newline character is at the end of each line in the text file. The print function adds its own newline each time we call it, so we end up with two newline characters at the end of each line: one from the file and one from print(). Using rstrip() on each line in the print() call eliminates these extra blank lines.

file_name = 'pi_digits.txt'with open(file_name) as file_object:    for line in file_object:        print(line.rstrip())
3.1415926535  8979323846  2643383279

Making a List of Lines from a File

When you use with, the file object returned by open() is only available inside the with block that contains it. If you want to retain access to a files contents outside the with block, you can store the files lines in a list inside the block and then work with that list. You can process parts of the file immediately and postpone some processing for later in the program.

The following example stores the lines of pi_digits. txt in a list inside the with block and then prints the lines outside the with block:

file_name = 'pi_digits.txt'with open(file_name) as object_file:    lines = object_file.readlines()for line in lines:    print(line.rstrip())
3.1415926535  8979323846  2643383279

At lines = object_file.readlines() the readlines() method takes each line from the file and stores it in a list. This list is then assigned to lines, which we can continue to work with after the with block ends.

At for line in lines: we use a simple for loop to print each line from lines. Because each item in lines corresponds to each line in the file, the output matches the contents of the file exactly.

Working with a Files Contents

After youve read a file into memory, you can do whatever you want with that data, so lets briefly explore the digits of pi. First, well attempt to build a single string containing all the digits in the file with no whitespace in it:

file_name = 'pi_digits.txt'with open(file_name) as object_file:    lines = object_file.readlines()pi_string = ''for line in lines:    pi_string += line.rstrip()print(pi_string)print(len(pi_string))
3.1415926535  8979323846  264338327936

We start by opening the file and storing each line of digits in a list, just as we did in the previous example. At pi_string = '' we create a variable, pi_string, to hold the digits of pi. We then create a loop that adds each line of digits to pi_string and removes the newline character from each line pi_string += line.rstrip().

The variable pi_string contains the whitespace that was on the left side of the digits in each line, but we can get rid of that by using strip() instead of rstrip():

--snip--for line in lines:    pi_string += line.strip()print(pi_string)print(len(pi_string))
3.14159265358979323846264338327932

Now we have a string containing pi to 30 decimal places. The string is 32 characters long because it also includes the leading 3 and a decimal point.

Please note that, When Python reads from a text file, it interprets all text in the file as a string. If you read in a number and want to work with that value in a numerical context, youll have to convert it to an integer using the int() function or convert it to a float using the float() function.

Large Files: One Million Digits

So far weve focused on analyzing a text file that contains only three lines, but the code in these examples would work just as well on much larger files. If we start with a text file that contains pi to 1,000,000 decimal places instead of just 30, we can create a single string containing all these digits. We dont need to change our program at all except to pass it a different file. Well also print just the first 50 decimal places, so we dont have to watch a million digits scroll by in the terminal:

filename = 'pi_million_digits.txt'with open(filename) as file_object:    lines = file_object.readlines()pi_string = ''for line in lines:    pi_string += line.strip()print(f"{pi_string[:52]}...")print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...1000002

The output shows that we do indeed have a string containing pi to 1,000,000 decimal places.

Python has no inherent limit to how much data you can work with; you can work with as much data as your systems memory can handle.

Is Your Birthday Contained in Pi?

Lets use the program we just wrote to find out if someones birthday appears anywhere in the first million digits of pi. We can do this by expressing each birthday as a string of digits and seeing if that string appears anywhere in pi_string:

filename = 'pi_digits.txt'with open(filename) as object_file:    lines = object_file.readlines()pi_string = ''for line in lines:    pi_string += line.strip()birthday = input("Enter your birthday, in the form mmddyy: ")if birthday in pi_string:    print("Your birthday appears in the first million digits of pi!")else:    print("Your birthday does not appear in the first million digits of pi.")

Once youve read from a file, you can analyze its contents in just about any way you can imagine.

Writing to a File

One of the simplest ways to save data is to write it to a file. When you write text to a file, the output will still be available after you close the terminal containing your programs output. You can examine output after a program finishes running, and you can share the output files with others as well. You can also write programs that read the text back into memory and work with it again later.

Writing to an Empty File

To write text to a file, you need to call open() with a second argument telling Python that you want to write to the file. To see how this works, lets write a simple message and store it in a file instead of printing it to the screen:

filename = 'programming.txt'with open(filename, 'w') as file_object:    file_object.write("I Love Programming.")

The call to open() in this example has two arguments. The first argument is still the name of the file we want to open. The second argument, 'w', tells Python that we want to open the file in write mode.

You can open a file in:

  • read mode ('r')
  • write mode ('w')
  • append mode ('a')
  • a mode that allows you to read and write to the file ('r+')

If you omit the mode argument, Python opens the file in read-only mode by default.

The open() function automatically creates the file youre writing to if it doesnt already exist. However, be careful opening a file in write mode ('w') because if the file does exist, Python will erase the contents of the file before returning the file object.

At file_object.write("I Love Programming.") we use the write() method on the file object to write a string to the file. This program has no terminal output, but if you open the file (programming. txt), youll see one line.

I love programming.

This file behaves like any other file on your computer. You can open it, write new text in it, copy from it, paste to it, and so forth.

Python can only write strings to a text file. If you want to store numerical data in a text file, youll have to convert the data to string format first using the str() function.

Writing Multiple Lines

The write() function doesnt add any newlines to the text you write. So if you write more than one line without including newline characters, your file may not look the way you want it to:

filename = 'programming.txt'with open(filename, 'w') as file_object:    file_object.write("I love programming.")    file_object.write("I love creating new games.")

If you open (programming. txt), youll see the two lines squished together:

I love programming.I love creating new games.

Including newlines in your calls to write() makes each string appear on its own line:

filename = 'programming.txt'with open(filename, 'w') as file_object:    file_object.write("I Love Programming.
") file_object.write("I love creating new games.
")
I love programming.I love creating new games.

You can also use spaces, tab characters, and blank lines to format your output, just as youve been doing with terminal-based output.

Appending to a File

If you want to add content to a file instead of writing over existing content, you can open the file in append mode. When you open a file in append mode, Python doesnt erase the contents of the file before returning the file object. Any lines you write to the file will be added at the end of the file. If the file doesnt exist yet, Python will create an empty file for you.

Lets modify last program by adding some new reasons we love programming to the existing file (programming. txt):

filename = 'programming.txt'with open(filename, 'a') as file_object:    file_object.write("I also love finding meaning in large datasets.
") file_object.write("I love creating apps that can run in a browser.
")

At with open(filename, 'a') as file_object: we use the 'a' argument to open the file for appending rather
than writing over the existing file. Then we write two new lines, which are added to (programming. txt).

I love programming.I love creating new games.I also love finding meaning in large datasets.I love creating apps that can run in a browser.

We end up with the original contents of the file, followed by the new content we just added.

Exceptions

Python uses special objects called exceptions to manage errors that arise during a programs execution. Whenever an error occurs that makes Python unsure what to do next, it creates an exception object. If you write code that handles the exception, the program will continue running. If you dont handle the exception, the program will halt and show a traceback, which includes a report of the exception that was raised.

Exceptions are handled with try-except blocks. A try-except block asks Python to do something, but it also tells Python what to do if an exception is raised. When you use try-except blocks, your programs will continue running even if things start to go wrong. Instead of tracebacks, which can be confusing for users to read, users will see friendly error messages that you write.

Handling the ZeroDivisionError Exception

Lets look at a simple error that causes Python to raise an exception. You probably know that its impossible to divide a number by zero, but lets ask Python to do it anyway:

print(5/0)
ZeroDivisionError: division by zero

Of course Python cant do this, so we get a traceback. The error reported in the traceback ZeroDivisionError, is an exception object. Python creates this kind of object in response to a situation where it cant do what we ask it to. When this happens, Python stops the program and tells us the kind of exception that was raised. We can use this information to modify our program. Well tell Python what to do when this kind of exception occurs; that way, if it happens again, were prepared.

Using try-except Blocks

When you think an error may occur, you can write a try-except block to handle the exception that might be raised. You tell Python to try running some code, and you tell it what to do if the code results in a particular kind of exception.

Heres what a try-except block for handling the ZeroDivisionError exception looks like:

try:    print(5/0)except ZeroDivisionError:    print("You can't divide by zero!")

We put print(5/0), the line that caused the error, inside a try block. If the code in a try block works, Python skips over the except block. If the code in the try block causes an error, Python looks for an except block whose error matches the one that was raised and runs the code in that block.

In this example, the code in the try block produces a ZeroDivisionError, so Python looks for an except block telling it how to respond. Python then runs the code in that block, and the user sees a friendly error message instead of a traceback:

You can't divide by zero!

If more code followed the try-except block, the program would continue running because we told Python how to handle the error. Lets look at an example where catching an error can allow a program to continue running.

Using Exceptions to Prevent Crashes

Handling errors correctly is especially important when the program has more work to do after the error occurs. This happens often in programs that prompt users for input. If the program responds to invalid input appropriately, it can prompt for more valid input instead of crashing.

Lets create a simple calculator that does only division:

while True:    first_number = input("
First Number: ") if first_number == 'q': break second_number = input("Second Number: ") if second_number == 'q': break answer = int(first_number) / int(second_number) print(answer)

This program prompts the user to input a first_number and, if the user does not enter 'q' to quit, a second_number. We then divide these two numbers to get an answer w. This program does nothing to handle errors, so asking it to divide by zero causes it to crash:

Give me two numbers, and I'll divide them.Enter 'q' to quit.First Number: 10Second Number: 52.0First Number: 5Second Number: 0Traceback (most recent call last):  File "division_calculator.py", line 13, in <module>    answer = int(first_number) / int(second_number)ZeroDivisionError: division by zero

Its bad that the program crashed, but its also not a good idea to let users see tracebacks. Nontechnical users will be confused by them, and in a malicious setting, attackers will learn more than you want them to know from a traceback. For example, theyll know the name of your program file, and theyll see a part of your code that isnt working properly. A skilled attacker can sometimes use this information to determine which kind of attacks to use against your code.

The else Block

We can make this program more error resistant by wrapping the line that might produce errors in a try-except block. The error occurs on the line that performs the division, so thats where well put the try-except block. This example also includes an else block. Any code that depends on the try block executing successfully goes in the else block:

print("Give me two numbers, and I'll divide them.")print("Enter 'q' to quit.")while True:    first_number = input("
First Number: ") if first_number == 'q': break second_number = input("Second Number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer)
Give me two numbers, and I'll divide them.Enter 'q' to quit.First Number: 10Second Number: 52.0First Number: 5Second Number: 0You can't divide by 0!First Number: q

We ask Python to try to complete the division operation in a try block, which includes only the code that might cause an error. Any code that depends on the try block succeeding is added to the else block. In this case if the division operation is successful, we use the else block to print the result.

The except block tells Python how to respond when a ZeroDivisionError arises. If the try block doesnt succeed because of a division by zero error, we print a friendly message telling the user how to avoid this kind of error. The program continues to run, and the user never sees a traceback.

The try-except-else block works like this: Python attempts to run the code in the try block. The only code that should go in a try block is code that might cause an exception to be raised. Sometimes youll have additional code that should run only if the try block was successful; this code goes in the else block. The except block tells Python what to do in case a certain exception arises when it tries to run the code in the try block.

By anticipating likely sources of errors, you can write robust programs that continue to run even when they encounter invalid data and missing resources. Your code will be resistant to innocent user mistakes and malicious attacks.

Handling the FileNotFoundError Exception

One common issue when working with files is handling missing files. The file youre looking for might be in a different location, the filename may be misspelled, or the file may not exist at all. You can handle all of these situations in a straightforward way with a try-except block.

Lets try to read a file that doesnt exist. The following program tries to read in the contents of A*lice in Wonderland*, but we havent saved the file (alice. txt) in the same directory as (alice. py):

filename = 'alice.txt'with open(filename, encoding='utf-8') as f:    contents = f.read()

There are two changes here. One is the use of the variable f to represent the file object, which is a common convention. The second is the use of the encoding argument. This argument is needed when your systems default encoding doesnt match the encoding of the file thats being read.

Python cant read from a missing file, so it raises an exception:

Traceback (most recent call last):File "alice.py", line 3, in <module>with open(filename, encoding='utf-8') as f:FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

The last line of the traceback reports a FileNotFoundError: this is the exception Python creates when it cant find the file its trying to open.

In this example, the open() function produces the error, so to handle it, the try block will begin with the line that contains open():

filename = 'alice.txt'try:    with open(filename, encoding='utf-8') as f:        contents = f.read()except FileNotFoundError:    print(f"Sorry, the file {filename} does not exist.")

In this example, the code in the try block produces a FileNotFoundError, so Python looks for an except block that matches that error. Python then runs the code in that block, and the result is a friendly error message instead of a traceback:

Sorry, the file alice.txt does not exist.

The program has nothing more to do if the file doesnt exist, so the error-handling code doesnt add much to this program. Lets build on this example and see how exception handling can help when youre working with more than one file.

Analyzing Text

You can analyze text files containing entire books. Many classic works of literature are available as simple text files because they are in the public domain. The texts used in this section come from Project Gutenberg (http://gutenberg.org/). Project Gutenberg maintains a collection of literary works that are available in the public domain, and its a great resource if youre interested in working with literary texts in your programming projects.

Lets pull in the text of Alice in Wonderland and try to count the number of words in the text. Well use the string method split(), which can build a list of words from a string. Heres what split() does with a string containing just the title "Alice in Wonderland":

>>> title = "Alice in Wonderland">>> title.split()['Alice', 'in', 'Wonderland']

The split() method separates a string into parts wherever it finds a space and stores all the parts of the string in a list. The result is a list of words from the string, although some punctuation may also appear with some of the words. To count the number of words in Alice in Wonderland, well use split() on the entire text. Then well count the items in the list to get a rough idea of the number of words in the text:

filename = 'alice.txt'try:    with open(filename, encoding='utf-8') as f:        contents = f.read()except FileNotFoundError:    print(f"Sorry, the file {filename} does not exist.")else:    # Count the approximate number of words in the file.    words = contents.split()    num_words = len(words)    print(f"The file {filename} has about {num_words} words.")

Move the file (alice. txt) to the correct directory, so the try block will work this time. At words = contents.split() we take the string contents, which now contains the entire text of Alice in Wonderland as one long string, and use the split() method to produce a list of all the words in the book. When we use len() on this list to examine its length, we get a good approximation of the number of words in the original string num_words = len(words).

Then we print a statement that reports how many words were found in the file. This code is placed in the else block because it will work only if the code in the try block was executed successfully. The output tells us how many words are in (alice. txt):

The file alice.txt has about 29465 words.

The count is a little high because extra information is provided by the publisher in the text file used here, but its a good approximation of the length of Alice in Wonderland.

Working with Multiple Files

Lets add more books to analyze. But before we do, lets move the bulk of this program to a function called count_words(). By doing so, it will be easier to run the analysis for multiple books:

def count_words(filename):    """Count the approximate number of words in a file."""    try:        with open(filename, encoding='utf-8') as f:            contents = f.read()    except FileNotFoundError:        print(f"Sorry, the file {filename} does not exist.")    else:        words = contents.split()        num_words = len(words)        print(f"The file {filename} has about {num_words} words.")

Most of this code is unchanged. We simply indented it and moved it into the body of count_words(). Its a good habit to keep comments up to date when youre modifying a program, so we changed the comment to a docstring and reworded it slightly.

Now we can write a simple loop to count the words in any text we want to analyze. We do this by storing the names of the files we want to analyze in a list, and then we call count_words() for each file in the list.

def count_words(filename):    --snip--filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']for filename in filenames:    count_words(filename)
The file alice.txt has about 29465 words.Sorry, the file siddhartha.txt does not exist.The file moby_dick.txt has about 215830 words.The file little_women.txt has about 189079 words.

The siddhartha. txt file is missed from the directory but it has no effect on the rest of the programs execution.

Using the try-except block in this example provides two significant advantages:

  • We prevent our users from seeing a traceback.
  • we let the program continue analyzing the texts its able to find.

If we dont catch the FileNotFoundError that 'siddhartha. txt' raised, the user would see a full traceback, and the program would stop running after trying to analyze Siddhartha. It would never analyze Moby Dick or Little Women.

Failing Silently

In the previous example, we informed our users that one of the files was unavailable. But you dont need to report every exception you catch. Sometimes youll want the program to fail silently when an exception occurs and continue on as if nothing happened. To make a program fail silently, you write a try block as usual, but you explicitly tell Python to do nothing in the except block. Python has a pass statement that tells it to do nothing in a block:

def count_words(filename):"""Count the approximate number of words in a file."""try:    --snip--except FileNotFoundError:    passelse:    --snip--filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']for filename in filenames:    count_words(filename)

The only difference between this listing and the previous one is the pass statement. Now when a FileNotFoundError is raised, the code in the except block runs, but nothing happens. No traceback is produced, and theres no output in response to the error that was raised. Users see the word counts for each file that exists, but they dont see any indication that a file wasnt found.

The file alice.txt has about 29465 words.The file moby_dick.txt has about 215830 words.The file little_women.txt has about 189079 words.

The pass statement also acts as a placeholder. Its a reminder that youre choosing to do nothing at a specific point in your programs execution and that you might want to do something there later. For example, in this program we might decide to write any missing filenames to a file called (missing_files. txt). Our users wouldnt see this file, but wed be able to read the file and deal with any missing texts.

Deciding Which Errors to Report

How do you know when to report an error to your users and when to fail silently? If users know which texts are supposed to be analyzed, they might appreciate a message informing them why some texts were not analyzed. If users expect to see some results but dont know which books are supposed to be analyzed, they might not need to know that some texts were unavailable. Giving users information they arent looking for can decrease the usability of your program. Pythons error-handling structures give you fine-grained control over how much to share with users when things go wrong; its up to you to decide how much information to share.

Well-written, properly tested code is not very prone to internal errors, such as syntax or logical errors. But every time your program depends on something external, such as user input, the existence of a file, or the availability of a network connection, there is a possibility of an exception being raised. A little experience will help you know where to include exception handling blocks in your program and how much to report to users about errors that arise.

Storing Data

Many of your programs will ask users to input certain kinds of information. You might allow users to store preferences in a game or provide data for a visualization. Whatever the focus of your program is, youll store the information users provide in data structures such as lists and dictionaries. When users close a program, youll almost always want to save the information they entered. A simple way to do this involves storing your data using the json module.

The json module allows you to dump simple Python data structures into a file and load the data from that file the next time the program runs. You can also use json to share data between different Python programs. Even better, the JSON data format is not specific to Python, so you can share data you store in the JSON format with people who work in many other programming languages. Its a useful and portable format, and its easy to learn.

The **JSON* (JavaScript Object Notation) format was originally developed for JavaScript. However, it has since become a common format used by many languages, including Python.*

Using json.dump() and json.load()

Lets write a short program that stores a set of numbers and another program that reads these numbers back into memory. The first program will use json.dump() to store the set of numbers, and the second program will use json.load().

The json.dump() function takes two arguments: a piece of data to store and a file object it can use to store the data. Heres how you can use json.dump() to store a list of numbers:

import jsonnumbers = [1, 2, 3, 4, 5, 10, 11, 15]filename = 'numbers.json'with open(filename, 'w') as f:    json.dump(numbers, f)

We first import the json module and then create a list of numbers to work with. At filename = 'numbers.json' we choose a filename in which to store the list of numbers. Its customary to use the file extension .json to indicate that the data in the file is stored in the JSON format. Then we open the file in write mode, which allows json to write the data to the file. At json.dump(numbers, f) we use the json.dump() function to store the list numbers in the file (numbers. json).

This program has no output, but lets open the file (numbers. json) and look at it. The data is stored in a format that looks just like Python:

[1, 2, 3, 4, 5, 10, 11, 15]

Now well write a program that uses json.load() to read the list back into memory:

import jsonfilename = 'numbers.json'with open(filename) as f:    numbers = json.load(f)print(numbers)
[1, 2, 3, 4, 5, 10, 11, 15]

At filename = 'numbers.json' we make sure to read from the same file we wrote to. This time when we open the file, we open it in read mode because Python only needs to read from the file. At numbers = json.load(f) we use the json.load() function to load the information stored in (numbers. json), and we assign it to the variable numbers. Finally we print the recovered list of numbers and see that its the same list created before.

This is a simple way to share data between two programs.

Saving and Reading User-Generated Data

Saving data with json is useful when youre working with user-generated data, because if you dont store your users information somehow, youll lose it when the program stops running. Lets look at an example where we prompt the user for their name the first time they run a program and then remember their name when they run the program again.

Lets start by storing the users name:

import jsonusername = input("What is you name? ")filename = 'username.json'with open(filename, 'w') as f:    json.dump(username, f)    print(f"We'll remember you when you come back, {username}!")
What is you name? AhmedWe'll remember you when you come back, Ahmed!

Now lets write a new program that greets a user whose name has already been stored:

import jsonfilename = 'username.json'with open(filename) as f:    username = json.load(f)    print(f"Welcome back, {username}!")
Welcome back, Ahmed!

We need to combine these two programs into one file. When someone runs remember_me. py, we want to retrieve their username from memory if possible; therefore, well start with a try block that attempts to recover the username. If the file (username. json) doesnt exist, well have the except block prompt for a username and store it in (username. json) for next time:

import json# Load the username, if it has been stored previously.# Otherwise, prompt for the username and store it.filename = 'username.json'try:    with open(filename) as f:        username = json.load(f)except FileNotFoundError:    username = input("What is your name? ")    with open(filename, 'w') as f:        json.dump(username, f)        print(f"We'll remember you when you come back, {username}!")else:    print(f"Welcome back, {username}!")

Theres no new code here; blocks of code from the last two examples are just combined into one file. Whichever block executes, the result is a username and an appropriate greeting. If this is the first time the program runs, this is the output:

What is you name? AhmedWe'll remember you when you come back, Ahmed!

Otherwise:

Welcome back, Ahmed!

This is the output you see if the program was already run at least once.

Refactoring

Often, youll come to a point where your code will work, but youll recognize that you could improve the code by breaking it up into a series of functions that have specific jobs. This process is called refactoring. Refactoring makes your code cleaner, easier to understand, and easier to extend.

We can refactor remember_me. py by moving the bulk of its logic into one or more functions. The focus of remember_me. py is on greeting the user, so lets move all of our existing code into a function called greet_user():

import jsondef greet_user():    """Greet the user by name."""    filename = 'username.json'    try:        with open(filename) as f:            username = json.load(f)    except FileNotFoundError:        username = input("What is your name? ")        with open(filename, 'w') as f:            json.dump(username, f)            print(f"We'll remember you when you come back, {username}!")    else:        print(f"Welcome back, {username}!")greet_user()

Because were using a function now, we update the comments with a docstring that reflects how the program currently works. This file is a little cleaner, but the function greet_user() is doing more than just greeting the userits also retrieving a stored username if one exists and prompting for a new username if one doesnt exist.

Lets refactor greet_user() so its not doing so many different tasks. Well start by moving the code for retrieving a stored username to a separate function:

import jsondef get_stored_username():    """Get stored username if available."""    filename = 'username.json'    try:        with open(filename) as f:            username = json.load(f)    except:        return None    else:        return usernamedef greet_user():    """Greet the user by name."""    username = get_stored_username()    if username:        print(f"Welcome back, {username}!")    else:        username = input("What is your name? ")        filename = 'username.json'        with open(filename, 'w') as f:            json.dump(username, f)            print(f"We'll remember you when you come back, {username}!")greet_user()

The new function get_stored_username() has a clear purpose, as stated in the docstring. This function retrieves a stored username and returns the username if it finds one. If the file (username. json) doesnt exist, the function returns None. This is good practice: a function should either return the value youre expecting, or it should return None. This allows us to perform a simple test with the return value of the function.

At if username: we print a welcome back message to the user if the attempt to retrieve a username was successful, and if it doesnt, we prompt for a new username.

We should refactor one more block of code out of greet_user(). If the username doesnt exist, we should move the code that prompts for a new username to a function dedicated to that purpose:

import jsondef get_stored_username():    """Get stored username if available."""    filename = 'username.json'    try:        with open(filename) as f:            username = json.load(f)    except:        return None    else:        return usernamedef get_new_username():    """Prompt for a new username."""    username = input("What is your name? ")    filename = 'username.json'    with open(filename, 'w') as f:        json.dump(username, f)    return usernamedef greet_user():    """Greet the user by name."""    username = get_stored_username()    if username:        print(f"Welcome back, {username}!")    else:        username = get_new_username()        print(f"We'll remember you when you come back, {username}!")greet_user()

Each function in this final version has a single, clear purpose. Each function in this final version of remember_me.py has a single, clear purpose. We call greet_user(), and that function prints an appropriate message: it either welcomes back an existing user or greets a new user. It does this by calling get_stored_username(), which is responsible only for retrieving a stored username if one exists. Finally, greet_user() calls get_new_username() if necessary, which is responsible only for getting a new username and storing it. This compartmentalization of work is an essential part of writing clear code that will be easy to maintain and extend.


Original Link: https://dev.to/ahmedgouda/python-files-and-exceptions-2f5i

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To