Python read-Write file operation

Source: Internet
Author: User
Tags glob

Python's function to read and write files is open or file

File_handler = open (Filename,,mode)

Table mode

Mode

Describe

R

Open the file as read to read the file information.

W

Open a file in write mode to write information to the file. If the file exists, empty the file, and then write the new content

A

Open a file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), and if the file does not exist, create

r+

The file can be read and written by opening the file in read/write mode.

w+

Remove the file contents, and then open the file as read-write.

A +

Open the file in read-write mode and move the file pointer to the end of the file.

B

Open the file in binary mode instead of in text mode. This mode is only valid for Windows or DOS, and Unix-like files are operated in binary mode.

Table File Object Methods

Method

Describe

F.close ()

Close the file, remember to open the file after opening () must remember to close it, otherwise it will occupy the system open file handle number.

F.fileno ()

Gets the file descriptor, which is a number

F.flush ()

Refresh Output Cache

F.isatty ()

Returns true if the file is an interactive terminal, otherwise false.

F.read ([Count])

Reads the file, and if there is count, it reads count bytes.

F.readline ()

Read a line of information.

F.readlines ()

Reads all the lines, that is, the information that reads the entire file.

F.seek (Offset[,where])

Move the file pointer to the offset position relative to where. Where 0 indicates the beginning of the file, this is the default, 1 is the current position, and 2 means the end of the file.

F.tell ()

Gets the file pointer position.

F.truncate ([size])

Intercepts the file so that the file size is sized.

F.write (String)

Writes string strings to a file.

F.writelines (list)

Writes a string in a list to a file in a row, and writes the file continuously without wrapping.

Here's an example: Read the file python code 1.read = Open (Result) 2.       Line=read.readline () 3.             While line:4. Print Line 5.       Line=read.readline () #如果没有这行会造成死循环 6.        Read.close Write file python code 1.read = file (result, ' A + ') 2.        Read.write ("\ r \ n") 3.        Read.write ("Thank You") 4. Read.close

Ii. getting information from an existing file using a module in Python, you can get information from an existing file. Use the OS module and the stat module to get basic information about the file: 1. Import OS 2. Import Stat 3.  Import time<div></div> 4. 5. Filestats = Os.stat (' Test.txt ') 6.     FileInfo = {7. ' Size ': filestats [Stat.     St_size], 8. ' LastModified ': Time.ctime (filestats [Stat.     St_mtime]), 9. ' LastAccessed ': Time.ctime (filestats [Stat.     St_atime]), 10. ' CreationTime ': Time.ctime (filestats [Stat.     St_ctime]), 11. ' Mode ': filestats [Stat. St_mode] 12.  } 13.     Infofield, Infovalue in fileinfo:15. Print Infofield, ': ' + infovalue 16. If Stat. S_isdir (filestats [Stat.     St_mode]): 17. print ' Directory.     ' Else:19. print ' non-directory. ' Import osimport statimport timefilestats = Os.stat (' test.txt ') FileInfo = {' Size ': filestats [s Tat. St_size], ' lastmodified ': Time.ctime (filestats [Stat. St_mtime]), ' lastaccessed ': Time.ctime (filestats [Stat. St_atime]), ' CreationTime ': Time.ctime (filestats [Stat. St_ctime]), ' Mode ': Filestats [Stat. St_mode]}for Infofield, infovalue in Fileinfo:print Infofield, ': ' + infovalueif Stat. S_isdir (filestats [Stat. St_mode]):p rint ' Directory. ' Else:print ' non-directory. ' The above example creates a dictionary that contains basic information about a file. It then displays the relevant information and tells us whether the open is a directory. We can also try to open whether there are several other types: 1. Import OS 2.  Import Stat 3. 4. Filestats = Os.stat (' Test.txt ') 5. FileMode = filestats [Stat. St_mode] 6. If Stat. S_isreg (filestats [Stat. St_mode]): 7. print ' Regular file. ' 8. Elif Stat. S_isdir (filestats [Stat. St_mode]): 9. print ' Directory. ' Elif Stat. S_islnk (filestats [Stat.     St_mode]): 11. print ' Shortcut. ' Elif Stat. S_issock (filestats [Stat.     St_mode]): 13. print ' Socket. ' Elif Stat. S_isfifo (filestats [Stat.     St_mode]): 15. print ' Named pipe. ' Elif Stat. S_ISBLK (filestats [Stat.     St_mode]): 17. print ' Block special device. ' Elif Stat. S_ISCHR (filestats [Stat.     St_mode]): 19. print ' Character special device. ' Import osimport statfilestats = OS.stat (' test.txt ') FileMode = filestats [Stat. St_mode]if Stat. S_isreg (filestats [Stat. St_mode]):p rint ' Regular file. ' Elif Stat. S_isdir (filestats [Stat. St_mode]):p rint ' Directory. ' Elif Stat. S_islnk (filestats [Stat. St_mode]):p rint ' Shortcut. ' Elif Stat. S_issock (filestats [Stat. St_mode]):p rint ' Socket. ' Elif Stat. S_isfifo (filestats [Stat. St_mode]):p rint ' Named pipe. ' Elif Stat. S_ISBLK (filestats [Stat. St_mode]):p rint ' Block special device. ' Elif Stat. S_ISCHR (filestats [Stat. St_mode]):p rint ' Character special device. ' In addition, we can use "Os.path" to get basic information: 1.  Import Os.path 2. 3. Filestats = ' test.txt ' 4. If Os.path.isdir (filestats): 5. print ' Directory. ' 6. Elif Os.path.isfile (filestats): 7. print ' File ' 8. Elif Os.path.islink (filestats): 9. print ' Shortcut. '     Elif Os.path.ismount (filestats): 11. print ' Mount point. ' Import os.pathfilestats = ' test.txt ' if Os.path.isdir (filestats):p rint ' Directory. ' Elif os.path.isfile (filestats):p Rint ' File. ' Elif Os.path.islink (filestats):p rint ' Shortcut. ' Elif Os.path.ismount (filestats):p rint ' Mount point. '

 

Third, the directory and ordinary files, the operation of the directory is also easy to grasp. First, list the contents of a directory: 1.  Import OS 2. 3. For fileName in Os.listdir ('/'): 4. Print filename import osfor filename in Os.listdir ('/'):p rint filename as you See, this is very simple, with three lines of code can be done. Creating a directory is also simple: 1.  Import OS 2. 3. Os.mkdir (' testdirectory ') import osos.mkdir (' testdirectory ') Delete the directory you just created: 1.  Import OS 2. 3. Os.rmdir (' testdirectory) import osos.rmdir (' testdirectory) Well, you can create a multilevel directory: 1.  Import OS 2. 3. Os.makedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ') import osos.makedirs (' i/will/show/you/how/deep/ The/rabbit/hole/goes ') If you do not add anything in the created folder, you can delete them all at once (that is, delete all the empty folders listed): 1.  Import OS 2. 3. Os.removedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ') import osos.removedirs (' i/will/show/you/how/ Deep/the/rabbit/hole/goes ') When you need to operate on a particular file type, we can select the "Fnmatch" module. Here is the contents of the ". txt" file and the filename of the ". exe" FILE: 1. Import Fnmatch 2.  Import OS 3. 4. For fileName in Os.listdir ('/'): 5. If Fnmatch.fnmath (filename, ' *.txt '): 6. Print open (filename).     Read () 7. ELif fnmatch.fnmatch (fileName, ' *.exe '): 8. Print fileName import fnmatchimport osfor filename in Os.listdir (' /'): If Fnmatch.fnmath (filename, ' *.txt '):p rint open (filename). Read () elif fnmatch.fnmatch (filename, ' *.exe '):p Rin The T fileName "*" character can represent any length of character. If you want to match one character, use the "?" Symbol: 1. Import Fnmatch 2.  Import OS 3. 4. For fileName in Os.listdir ('/'): 5. If fnmatch.fnmatch (filename, '?. TXT '): 6. print ' Text file. ' Import fnmatchimport osfor fileName in Os.listdir ('/'): If Fnmatch.fnmatch (filen Ame, '?. TXT '):p rint ' Text file. ' " Fnmatch "module supports regular expressions: 1. Import Fnmatch 2. Import OS 3.  Import re 4. 5. Filepattern = Fnmatch.translate (' *.txt ') 6. For FileName in Os.listdir ('/'): 7. If Re.match (Filepattern, FileName): 8. print ' Text file. ' Import FNM Atchimport Osimport Refilepattern = fnmatch.translate (' *.txt ') for FileName in Os.listdir ('/'): If Re.match (Filepatt Ern, FileName):p rint ' Text file. ' If you only need to match one type of file, a better way is to use the "Glob" module. The format of the module and the "FNMATCH "similar: 1.  Import Glob 2.  3. For fileName in Glob.glob (' *.txt '): 4. print ' Text file. ' Import globfor fileName in Glob.glob (' *.txt '):p rint ' Text file. ' Using a range of characters to match is also possible, just as it is used in regular expressions. Assume that you want to display the file name of only one digit before the extension: 1.  Import Glob 2. 3. For fileName in Glob.glob (' [0-9].txt '): 4. Print filename import globfor the filename in Glob.glob (' [0-9].txt '):p The rint filename "Glob" module is implemented using the "Fnmatch" module. Iv. data grouping use the modules described in the previous section to read and write strings in a file. However, sometimes you may need to pass other types of data, such as list, tuple, dictionary, and other objects. In Python, you can use pickling to do this. You can use the "pickle" module in the Python standard library to complete the data grouping. Next, let's group A list:1 that contains strings and numbers.  Import Pickle 2. 3. FileHandle = open (' PickleFile.txt ', ' W ') 4. Testlist = [' This ', 2, ' is ', 1, ' A ', 0, ' Test. '] 5. Pickle.dump (Testlist, FileHandle) 6. Filehandle.close () Import picklefilehandle = open (' PickleFile.txt ', ' w ') testlist = [' This ', 2, ' is ', 1, ' A ', 0, ' Test. ']pickle.dump (testlist, FileHandle) filehandle.close () Split grouping is also not difficult: 1.  Import Pickle 2. 3. FileHandle = open (' PickleFile.txt ') 4. Testlist = PICKLE.LOad (FileHandle) 5. Filehandle.close () Import picklefilehandle = open (' pickleFile.txt ') testlist = Pickle.load (filehandle) Filehandle.clos E () Now try to store more complex data: 1.  Import Pickle 2. 3. FileHandle = open (' PickleFile.txt ', ' W ') 4. Testlist = [123, {' Calories ': ', ', ' Mr Anderson ', [1, 2, 7]] 5. Pickle.dump (Testlist, FileHandle) 6. Filehandle.close () Import picklefilehandle = open (' PickleFile.txt ', ' w ') testlist = [123, {' Calories ': Derson ', [1, 2, 7]]pickle.dump (testlist, FileHandle) filehandle.close () 1.  Import Pickle 2. 3. FileHandle = open (' PickleFile.txt ') 4. Testlist = Pickle.load (filehandle) 5. Filehandle.close () Import picklefilehandle = open (' pickleFile.txt ') testlist = Pickle.load (filehandle) Filehandle.clos E () As mentioned above, using Python's "pickle" module grouping is really simple. Many objects can be stored in a file by it. If possible, "Cpickle" is equally qualified for the job. It is the same as the "pickle" module, but faster: 1.  Import Cpickle 2. 3. FileHandle = open (' PickleFile.txt ', ' W ') 4. Cpickle.dump (1776, FileHandle) 5. Filehandle.close () IMport cpicklefilehandle = open (' PickleFile.txt ', ' W ') Cpickle.dump (1776, FileHandle) Filehandle.close () v. Create "virtual" files you use. Many modules contain methods that require a file object as a parameter. However, sometimes it is difficult to create and use a real file. Fortunately, in Python, you can use the "Stringio" module to create a file and save it in memory: 1.  Import Stringio 2. 3. FileHandle = Stringio.stringio ("Let Freedom Ring") 4. Print Filehandle.read () # "Let Freedom Ring." 5. Filehandle.close () Import stringiofilehandle = Stringio.stringio ("Let Freedom Ring") print Filehandle.read () # "Let F Reedom ring. " The Filehandle.close () Cstringio "module is also valid. It uses the same method as "Stringio", but like "cpickle" to "pickle", it is faster: 1.  Import Cstringio 2. 3. FileHandle = Cstringio.cstringio ("To Kill a Mockingbird") 4. Print Filehandle.read () # "to Kill a Mockingbid" 5. Filehandle.close () Import cstringiofilehandle = Cstringio.cstringio ("To Kill a Mockingbird") print Filehandle.read () # " To Kill a mockingbid "filehandle.close () conclusion file management, is the problem that programmers in many programming languages often encounter when writing applications. Fortunately, Python makes it surprisingly easy to compare with other languages. Python's standard library provides a number of related modules to help programmers solve this problem, and its object-oriented mechanism simplifies the operation. Well, now that you've learned about the file tubes in PythonCan be used well in future applications, with the basics of  

Version vbbb

Python read-Write file operation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.