1 This is a file that is created and written to a new file in the console.
#!/usr/bin/env python ' maketextfile.py--Create text file ' import os ls = os.linesep #get filename while True : fname = raw_input (' Enter filename: ') if Os.path.exists (fname): print "ERROR: '%s ' already exists"% fname< C7/>else: break #get The file content (text) lines all = [] print "\nenter lines ('. ' by itself to quit). \ n" #loop Until user terminates input while True: entry = raw_input (' > ') if entry = = '. ': Break Else: All.append (entry) #write lines to file with proper line-ending fobj = open (fname, ' W ') fobj.writelines (['%s%s '% (x, LS) fobj.close () print ' done! ' os.linesep represents the line end flag, which saves time by replacing it with the local variable name LS and reduces the consumption of system resources. Read the file name with Raw_input () in the list all[] To save each line of text (they are temporarily in memory). After the last creation of the file, use Writelines () to write the in-memory rows to the open file.
2. This is a small program that reads the contents of a particular file.
#!/usr/bin/env python ' readtextfile.py--read and display text file ' #get filename fname = raw_input (' Enter filen Ame: ') print #attempt to open file for reading try: fobj = open (fname, ' R ') except IOError, E: print "* * * fil E Open error: ", E else: #display contents to the screens for Eachline in Fobj: print Eachline,
(1) Note: Since we did not remove the line terminator representing the end of each line, we had to resist the line terminator automatically generated by the print statement--by adding a comma at the end of the print statement to achieve this
No comma after print is this effect:
(2) Try-except-else is a new statement, where the EXCEPT clause is where we handle the error.
Note: Two programs need to add executable permissions to the file before execution.
$chmod a+x filename