Share a simple python file read/write script,
Let's take a look at the code for creating a file and writing text, and then introduce it.
#!/usr/bin/env python 'makeFile.py -- create a file' import os ls = os.linesep # get filename while True: fname = raw_input('Input an unused file name >') if os.path.exists(fname): print "ERROR: '%s' already exists" %fname else: break # get file content lines all = [] print "\nEnter lines (input '.' 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' if __name__ == '__main__': print 'innter module'
The code above is used to create a new file and write the text. Line 3 sets the linesep in the OS module to the alias ls. This simplifies the long variable name, on the other hand, it is also mainly used to improve code performance, because when accessing this variable, we must first check the OS module and then parse linesep. linesep is the line terminator mark, and '\ R' in linux ', in windows, it is '\ r \ n'. It is better to save it with local variables. The 34th line uses _ name __, which is mainly used for in-code testing. Its value is _ main __, but the python file is usually used as a module by other files for import, in this case, the value of _ name _ is the module name, and the test code in the module will not be executed.
#!/usr/bin/env python 'readFile.py -- read and display 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()
The above code is used to read a file and display its content on the screen. the try-try t-else exception handling mechanism is used.
Here is a brief introduction to the working principle of try: After a try statement is started, python marks it in the context of the current program, so that when an exception occurs, you can return here, the try clause is executed first. What will happen next depends on whether exceptions occur during execution.
#1. If an exception occurs when executing the try statement, python will jump back to try and execute the first limit t clause that matches the exception. The Exception Processing is complete, the control flow uses the entire try Statement (unless a new exception is thrown when an exception is handled ).
#2. If an exception occurs in the statement after try, but there is no matching limit t clause, the exception will be submitted to the try at the upper layer, or to the top of the Program (this will end the program and print the default error information ).
#3. If no exception occurs during the execution of the try clause, python will execute the statement after the else Statement (if else exists) and then control the flow through the entire try statement.
Summary
The above is all the content of a simple python script for reading and writing files. I hope it will be helpful to you. If you have any shortcomings, please leave a message. Thank you for your support!