Two small examples of using Python scripts to operate files are shared.
1. This is a file that is created and written to the 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 else: break # get 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) for x in all]) fobj. close () print 'done! 'OS. linesep indicates the end mark of the line. It is replaced by the local variable name ls, saving time and reducing system resource consumption. use raw_input () to read the file name and use the list all [] to save each line of text (they are temporarily in memory ). after creating the file, use writelines () to write the rows in the memory to the open file.
2. This is a small program that reads the content of a specific file.
#!/usr/bin/env python 'readTextFile.py -- read and display text file' #get filename fname = raw_input('Enter filename: ') print #attempt to open file for reading try: fobj = open(fname, 'r') except IOError, e: print "*** file open error:", e else: #display contents to the screen for eachLine in fobj: print eachLine, fobj.close()
(1) Note: because we have not removed the line terminator representing the end of each line, we have to resist the row Terminator automatically generated by the print statement-this can be achieved by adding a comma at the end of the print statement.
There is no comma after print, which is the effect:
(2) try-try t-else is a new statement. The limit t clause is the place where we handle errors.
Note: Before executing the two programs, you must add executable permissions to the files.
$chmod a+x filename