The simplest stream (I/O) operation in Python is actually input and output. We all know to use output functions
print( str , end = '\n')
However, python has two input methods. One is the most commonly used input, but Python also has a raw_input functions can also be input, so what is the difference between them?
raw_input([prompt]) Read a line from the standard input, which is the data entered by the keyboard, and return a string (remove the line feed at the end), prompt Is a prompt statement For example: str = raw_input("Please enter:") print "What did you enter: ", str result: Please enter: Hello Python! What did you enter: Hello Python!
But input, this function supports raw_ In addition to the same function of input, it also has a special feature, which can identify the Python code in the input data
To learn more about stream operation, we need to talk about the operation file API that Python has like other languages, and Python's file API is more concisestr = input("Please enter:") print "What did you enter: ", str For example: Input:[x*5 for x in range(2,10,2)] result: What did you enter: [10, 20, 30, 40]
open(name,mode,buffering) name Is the file path, mode Is the access mode, which returns a file object,buffering Is a register area, that is, the identification of the character buffer,If buffering If the value of is set to 0, the file will not be cached. If buffering If the value of is 1, the line will be registered when accessing the file. If will buffering The value of is set to an integer greater than 1, indicating that this is the buffer size of the register. If a negative value is taken, the buffer size of the deposit area is the system default
The mode mode supports the following parameters, and the commonly used ones are only read and written
In the rookie tutorial, several common patterns are listed, and the illustrations are used for straightforward explanation
The following table is provided to explain several common modes and what functions can be realized
At the same time, you can know the following information according to the object returned by the open method
fo = open("foo.txt", "w") print "file name: ", fo.name print "Is it closed : ", fo.closed print "Access mode : ", fo.mode print "Whether to force spaces at the end : ", fo.softspace
After you open a file and use it, be sure to close it, otherwise your memory will be occupied
File object.close()
After calling the method of closing the stream, Python will refresh the contents of the cache into the file, and then it can no longer be written
Python's file object also provides many other methods for manipulating files, such as write methods
File object.write(str)
When writing a method, it should be noted that str in the stream does not have to be a string, but can be binary data, and the method will not automatically add a newline symbol
# Open a file fo = open("foo.txt", "w") fo.write( "www.runoob.com!\nVery good site!\n") # Close open files fo.close() There will be the following contents in the file: www.runoob.com! Very good site!
The file object also provides a method to read the content, read()
File object.read(num) Read the file, num Is the number of bytes. All contents are read when not writing # Open a file fo = open("foo.txt", "r+") str = fo.read(10) print "The read string is : ", str # Close open files fo.close() The read string is : www.runoob
Of course, the readline method can read a line. When the file you want to read is very large, it is no longer suitable to use read, and the string returned by readline contains line breaks
file = open('foo.txt', 'r' ) while True: text_line = file.readline() if text_line: print(text_line) else: break
The readline function can also pass in a parameter with the same meaning as the num of read to control the size of bytes read. However, it is generally not used. After all, only one line of data is read
Of course, Python also has a readlines function. Its use is somewhat risky because it also reads the entire file, but its return result is a list. Each line of data contains a newline character as each element of the list
Document content: 1:www.runoob.com 2:www.runoob.com 3:www.runoob.com 4:www.runoob.com 5:www.runoob.com fo = open("runoob.txt", "r") print "The file name is: ", fo.name for line in fo.readlines(): #Read each row in turn line = line.strip() #Remove the blanks at the beginning and end of each line print "The data read is: %s" % (line) # Close file fo.close()
When it comes to the reading method, we have to say that the file is located, that is, the position of the cursor when reading the file
The tell() method tells you the current location in the file. In other words, the next read and write will occur after so many bytes at the beginning of the file.
seek(offset [,from] )Method to change the location of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference location at which the bytes are to be moved. If from is set to 0, this means that the beginning of the file is used as the reference position for moving bytes. If set to 1, the current position is used as the reference position. If it is set to 2, the end of the file will be used as the reference location.
# Open a file fo = open("foo.txt", "r+") str = fo.read(10) print "The read string is : ", str # Find current location position = fo.tell() print "Current file location : ", position # Reposition the pointer to the beginning of the file again position = fo.seek(0, 0) str = fo.read(10) print "Reread string : ", str # Close open files fo.close() result: The read string is : www.runoob Current file location : 10 Reread string : www.runoob
In addition to reading and writing files, the most basic are renaming and deleting
import os , shutil os.rename(current_file_name, new_file_name) The two parameters of the rename method are the old and new paths with file names os.remove(file_name) Delete a file shutil.move() move file
Of course, there are many practical methods for the os module we import
os.mkdir(newdir) Create a new directory. Note that this method can only create a new directory. If you want to create a new file, you can consider it open method os.chdir(newdir) This method is used to set the current path of the current program operation, which is less used os.getcwd() This method is used to display the current path Python It is called the current working directory for the program os.rmdir(dirname) This method is used to delete a directory, but note that its child data should be deleted before deleting a directory os.listdir(catalogue) Get all file names in the directory shutil Module: Yes python Built in advanced file, folder and compressed package processing module shutil.copyfile(src,dst) take src Copy to dst In the middle, dst Be sure to have read-write permission if dst It already exists and will be overwritten, src and dst Must be a file, not a directory. shutil.move(src,dst) Move files and directories. Or rename the file or directory, if dst If it exists, it cannot be overwritten. shutil.copt(src,dst) Copy a file to a file or directory, src Must be a file, dst Is it a file or directory shutil.copy2(src,dst) stay copy The last access time and modification time are also copied, but the creation time will not be the same as the source file. shutil.copytree(olddir,newdir,True/False) hold olddir Make a copy newdir,If the third parameter is True,The symbolic link under the folder will be maintained when copying the directory. If there are three parameters, the False,A physical copy will be generated in the replicated directory instead of a symbolic connection
The file object and the os module we imported above can cooperate with each other to realize many operations. When you use it, you can find it on the Internet. It is recommended that you can take a look at the rookie tutorial, File object API --------- os object API