Chapter 10. Systems
One thing a computer can do that most humans can’t is be sealed up in a cardboard box and sit in a warehouse.
Jack Handey
In your everyday use of a computer, you do such things as list the contents of a folder or directory, create and remove files, and other housekeeping that’s necessary if not particularly exciting. You can also carry out these tasks, and more, within your own Python programs. Will this power drive you mad or cure your insomnia? We’ll see.
Python provides many system functions through a module named os (for
“operating system”), which we’ll import for all the programs in this
chapter.
Files
Python, like many other languages,
patterned its file operations after Unix.
Some functions, such as chown() and chmod(),
have the same names,
but there are a few new ones.
Create with open()
“File Input/Output” introduced you to the open() function and explains how you can use it to open a file or create one if it doesn’t already exist.
Let’s create a text file called oops.txt:
>>>fout=open('oops.txt','wt')>>>('Oops, I created a file.',file=fout)>>>fout.close()
With that done, let’s perform some tests with it.
Check Existence with exists()
To verify whether the file or directory is really there or you just imagined it, you can provide exists(), with a relative or absolute pathname, as demonstrated here:
>>>importos>>>os.path.exists('oops.txt')True>>>os.path.exists('./oops.txt')True>>>os.path.exists('waffles')False>>>os
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access