您在這裡

Example: Cleaning up a photo directory

24 二月, 2015 - 15:02

Some time ago, I built a bit of Flickr-like software that received photos from my cell phone and stored those photos on my server. I wrote this before Flickr existed and kept using it after Flickr existed because I wanted to keep original copies of my images forever.

I would also send a simple one-line text description in the MMS message or the subject line of the e-mail message. I stored these messages in a text file in the same directory as the image file. I came up with a directory structure based on the month, year, day and time the photo was taken. The following would be an example of the naming for one photo and its existing description:

./2006/03/24-03-06_2018002.jpg./2006/03/24-03-06_2018002.txt

After seven years, I had a lot of photos and captions. Over the years as I switched cell phones, sometimes my code to extract the caption from the message would break and add a bunch of useless data on my server instead of a caption. I wanted to go through these files and figure out which of the text files were really captions and which were junk and then delete the bad files. The first thing to do was to get a simple inventory of how many text files I had in of the sub-folders using the following program:

import oscount = 0for (dirname, dirs, files) in os.walk('.'):    for filename in files:        if filename.endswith('.txt') :            count = count + 1print 'Files:', count
python txtcount.pyFiles: 1917

The key bit of code that makes this possible is the os.walk library in Python. When we call os.walk and give it a starting directory, it will “walk” through all of the directories and sub-directories recursively. The string “.” indicates to start in the current directory and walk downward. As it encounters each directory, we get three values in a tuple in the body of the for loop. The first value is the current directory name, the second value is the list of sub-directories in the current directory, and the third value is a list of files in the current directory.

We do not have to explicitly look into each of the sub-directories because we can count on os.walk to visit every folder eventually. But we do want to look at each file, so we write a simple for loop to examine each of the files in the current directory. We check each file to see if it ends with “.txt” and then count the number of files through the whole directory tree that end with the suffix “.txt”.

Once we have a sense of how many files end with “.txt”, the next thing to do is try to automatically determine in Python which files are bad and which files are good. So we write a simple program to print out the files and the size of each file:

import osfrom os.path import joinfor (dirname, dirs, files) in os.walk('.'):    for filename in files:        if filename.endswith('.txt') :            thefile = os.path.join(dirname,filename)            print os.path.getsize(thefile), thefile

Now instead of just counting the files, we create a file name by concatenating the directory name with the name of the file within the directory using os.path.join. It is important to use os.path.join instead of string concatenation because on Windows we use a backslash (\) to construct file paths and on Linux or Apple we use a forward slash (/) to construct file paths. The os.path.join knows these differences and knows what system we are running on and it does the proper concatenation depending on the system. So the same Python code runs on either Windows or Unix-style systems.

Once we have the full file name with directory path, we use the os.path.getsize utility to get the size and print it out, producing the following output:

python txtsize.py...18 ./2006/03/24-03-06_2303002.txt22 ./2006/03/25-03-06_1340001.txt22 ./2006/03/25-03-06_2034001.txt...2565 ./2005/09/28-09-05_1043004.txt2565 ./2005/09/28-09-05_1141002.txt...2578 ./2006/03/27-03-06_1618001.txt2578 ./2006/03/28-03-06_2109001.txt2578 ./2006/03/29-03-06_1355001.txt...

Scanning the output, we notice that some files are pretty short and a lot of the files are pretty large and the same size (2578 and 2565). When we take a look at a few of these larger files by hand, it looks like the large files are nothing but a generic bit of identical HTML that came in from mail sent to my system from my T-Mobile phone:

<html>    <head>        <title>T-Mobile</title>...

Skimming through the file, it looks like there is no good information in these files so we can probably delete them.

But before we delete the files, we will write a program to look for files that are more than one line long and show the contents of the file. We will not bother showing ourselves those files that are exactly 2578 or 2565 characters long since we know that these files have no useful information.

So we write the following program:

import osfrom os.path import joinfor (dirname, dirs, files) in os.walk('.'):    for filename in files:        if filename.endswith('.txt') :            thefile = os.path.join(dirname,filename)            size = os.path.getsize(thefile)            if size == 2578 or size == 2565:                continue            fhand = open(thefile,'r')            lines = list()            for line in fhand:                lines.append(line)            fhand.close()            if len(lines) > 1:                print len(lines), thefile                print lines[:4]

We use a continue to skip files with the two “bad sizes”, then open the rest of the files and read the lines of the file into a Python list and if the file has more than one line we print out how many lines are in the file and print out the first three lines.

It looks like filtering out those two bad file sizes, and assuming that all one-line files are correct, we are down to some pretty clean data:

python txtcheck.py3 ./2004/03/22-03-04_2015.txt['Little horse rider\r\n', '\r\n', '\r']2 ./2004/11/30-11-04_1834001.txt['Testing 123.\n', '\n']3 ./2007/09/15-09-07_074202_03.txt['\r\n', '\r\n', 'Sent from my iPhone\r\n']3 ./2007/09/19-09-07_124857_01.txt['\r\n', '\r\n', 'Sent from my iPhone\r\n']3 ./2007/09/20-09-07_115617_01.txt...

But there is one more annoying pattern of files: there are some three-line files that consist of two blank lines followed by a line that says “Sent from my iPhone” that have slipped into my data. So we make the following change to the program to deal with these files as well.

lines = list()for line in fhand:    lines.append(line)if len(lines) == 3 and lines[2].startswith('Sent from my iPhone'):    continueif len(lines) > 1:    print len(lines), thefile    print lines[:4]

We simply check if we have a three-line file, and if the third line starts with the specified text, we skip it.

Now when we run the program, we only see four remaining multi-line files and all of those files look pretty reasonable:

python txtcheck2.py3 ./2004/03/22-03-04_2015.txt['Little horse rider\r\n', '\r\n', '\r']2 ./2004/11/30-11-04_1834001.txt['Testing 123.\n', '\n']2 ./2006/03/17-03-06_1806001.txt['On the road again...\r\n', '\r\n']2 ./2006/03/24-03-06_1740001.txt['On the road again...\r\n', '\r\n']

If you look at the overall pattern of this program, we have successively refined how we accept or reject files and once we found a pattern that was “bad” we used continue to skip the bad files so we could refine our code to find more file patterns that were bad.

Now we are getting ready to delete the files, so we are going to flip the logic and instead of printing out the remaining good files, we will print out the “bad” files that we are about to delete.

import osfrom os.path import joinfor (dirname, dirs, files) in os.walk('.'):for filename in files:if filename.endswith('.txt') :thefile = os.path.join(dirname,filename)size = os.path.getsize(thefile)if size == 2578 or size == 2565:print 'T-Mobile:',thefilecontinuefhand = open(thefile,'r')lines = list()for line in fhand:lines.append(line)fhand.close()if len(lines) == 3 and lines[2].startswith('Sent from my iPhone'):print 'iPhone:', thefilecontinue

We can now see a list of candidate files that we are about to delete and why these files are up for deleting. The program produces the following output:

python txtcheck3.py...T-Mobile: ./2006/05/31-05-06_1540001.txtT-Mobile: ./2006/05/31-05-06_1648001.txtiPhone: ./2007/09/15-09-07_074202_03.txtiPhone: ./2007/09/15-09-07_144641_01.txtiPhone: ./2007/09/19-09-07_124857_01.txt...

We can spot-check these files to make sure that we did not inadvertently end up introducing a bug in our program or perhaps our logic caught some files we did not want to catch.

Once we are satisfied that this is the list of files we want to delete, we make the following change to the program:

        if size == 2578 or size == 2565:            print 'T-Mobile:',thefile            os.remove(thefile)            continue...        if len(lines) == 3 and lines[2].startswith('Sent from my iPhone'):            print 'iPhone:', thefile            os.remove(thefile)            continue

In this version of the program, we will both print the file out and remove the bad files using os.remove.

python txtdelete.pyT-Mobile: ./2005/01/02-01-05_1356001.txtT-Mobile: ./2005/01/02-01-05_1858001.txt...

Just for fun, run the program a second time and it will produce no output since the bad files are already gone.

If we re-run txtcount.py we can see that we have removed 899 bad files:

python txtcount.py

Files: 1018

In this section, we have followed a sequence where we use Python to first look through directories and files seeking patterns. We slowly use Python to help determine what we want to do to clean up our directories. Once we figure out which files are good and which files are not useful, we use Python to delete the files and perform the cleanup.

The problem you may need to solve can either be quite simple and might only depend on looking at the names of files, or perhaps you need to read every single file and look for patterns within the files. Sometimes you will need to read all the files and make a change to some of the files. All of these are pretty straightforward once you understand how os.walk and the other os utilities can be used.