Description
Python is really a lot more concise than other languages, and in the process of learning C, at least to the very back of the file operation, but Python QuickStart in a very concise way to let you have a file operation experience, of course, this is in the Linux environment, But it has to be said that the Linux environment for programming learning is really more than Windows can learn more knowledge, the following two examples are from the "Python Core programming" book, really very classic!
I. Creating and writing an instance of a file
Directly to the code:
#!/usr/bin/env python ' Maketextfile.py -- create text file ' import osls = os.linesep# get filenamewhile true: fname = raw_input (' Please input the filename: ') if os.path.exists (fname): print "error: '%s ' already exists" % fname else: break# get file content (text) linesall = []print "\nenter lines ('. ') by itself to quit) \ n "# loop until user terminates inputwhile true: entry = raw_input (' > ') if entry == '. ': break else: all.append (Entry) # write lines to file with proper line-endingfobj = open (fname, ' W ') fobj.writelines (['%s%s '  %  (X, LS) for x in all]) fobj.close () print ' done! '
Save as a. py file and run as prompted to create a file that contains your input.
Two. File read and display instances
Directly to the code:
#!/usr/bin/env python ' readtextfile.py--read and display text file ' # Get filenamefname = raw_input (' Enter filename: ') pri nt# attempt to open file for readingtry:fobj = open (fname, ' R ') except IOError, e:print "* * * File Open error:", Eelse: # Display contents to the screens for Eachline in Fobj:print Eachline, Fobj.close ()
Just read the file itself does not need so much code, but here also added the function of exception handling, very user-friendly! Save as a. py file, you can read the file created above to try it.
This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1691111
QuickStart instances of file read and write in Python