|
||||
|
« Beginning Python Tutorial (Part 6) | Heavy Weapons available at CMRPG » |
Beginning Python Tutorial (Part 7)
by: crystalattice - Oct 07, 2005
Working with FilesThe final built-in object type of Python allows us to access files. The open() function creates a Python file object, which links to an external file. After a file is opened, you can read and write to it like normal. Files in Python are different from the previous types I've covered. They aren't numbers, sequences, nor mappings; they only export methods for common file processing. Technically, files are a prebuilt C extension that provides a wrapper for the C stdio filesystem. If you already know how to use C files, you pretty much know how to use Python files. But to keep things consistent, here's the list of Python file operations:
Because Python has a built-in garbage collector, you don't really need to manually close your files; once an object is no longer referenced within memory, the object's memory space is automatically reclaimed. This applies to all objects in Python, including files. However, it's recommend to manually close files in large systems because it won't hurt anything. When a file is read, such as with a readline() method, the end of the file is shown shown at the command line with an empty string; empty lines are just strings with an end-of-line character. Here's an example: Generic Code Example: >>> myfile = open('myfile', 'w') # open for output (creates) >>> myfile.write('hello text file\n') # write a line of text >>> myfile.close() >>> myfile = open('myfile', 'r') # open for input >>> myfile.readline() # read the line back 'hello text file\012' >>> myfile.readline() # empty string: end of file Well, that's it for these initial tutorials. You've seen all the data types and built-in data structures Python provides and you've seen how to use them in a basic fashion. The next few tutorials will show general object properties, boolean truth and comparison, and some of the built-in "gotchas" of the Python language. After that, I'll talk about basic statements (including loops), functions, modules, classes, and exceptions. I don't know how many tutorials this will cover, nor how long it will take me to write them, but I hope you enjoy them. As usual, if you want more in-depth knowledge or additional information, visit the official Python web site.
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Beginning Python Tutorial (Part 6) | Heavy Weapons available at CMRPG » |