Python Study Notes (12) Python files and iterations (1 ),

Source: Internet
Author: User

Python Study Notes (12) Python files and iterations (1 ),

File

Files and folders

Files: text files, binary files

Folder: (windows) G: \ pythonWorkspace \ python \ study

(Linux/mac)/home/workspace/python

Note: The slash of the folder path is different from that of windows.

File Path in windows: Example

1 >>> p1="G:\pythonWorkspace\python\study\test.txt"2 >>> p2 =r"G:\pythonWorkspace\python\study\test.txt"3 >>> p3 ="G:\\pythonWorkspace\\python\\study\\test.txt"

 

Cross-platform path: OS. path. abspath (path)

View attributes: OS. stat (filename)

 
p2 =r"G:\pythonWorkspace\python\study\test.txt"
1 >>> import OS # introduce the OS Module
2 >>> OS. stat (p2) # View File Attributes 3 nt. stat_result (st_mode = 33206, st_ino = 0L, st_dev = 0L, st_nlink = 0, st_uid = 0, st_gid = 0, st_size = 14L, st_atime = 15209532.16l, st_mtime = hour, st_ctime = 1520953366l) 4 >>>

 

Read and Write files

Files in python are also a type of object with the attribute _ iter __, which indicates that objects can be iterated.

Open a file

>>> Dir (file) # view the object attributes ['_ class _', '_ delattr _', '_ doc __', '_ enter _', '_ exit _', '_ format _', '_ getattribute _', '_ hash __', '_ init _', '_ iter _', '_ new _', '_ reduce _', '_ performance_ex __', '_ repr _', '_ setattr _', '_ sizeof _', '_ str _', '_ subclasshook __', 'close', 'closed ', 'encoding', 'errors', 'fileno', 'flused', 'isatty', 'Mode', 'name', 'newlines ', 'Next', 'read', 'readin', 'readline', 'readlines', 'sece', 'softspace', 'ttel', 'truncate', 'write ', 'writelines ', 'xreadlines'] >>> f = open (p2) # open a file >>> for line in f: # Read the file content cyclically... print line # When printed, there are no rows between the two rows. The reason is that print automatically carries a line break... study pythonaaaaa >>> f = open (p2) # open the file for the second time >>> for line in f :... print line, # The empty line solution is added after line ,... study pythonaaaaa >>>

Write files

Open a file in w mode for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.

Open a file in a mode for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.

With statement can not write close ()

1 >>> nf = open ("G: \ pythonWorkspace \ python \ study \ test.txt", "w") # open a file in w mode, write 2> nf. write ("This is a new file. ") # Write this sentence to a file 3> nf. close () # open a file and close it after writing. 4 >>> nf = open ("G: \ pythonWorkspace \ python \ study \ test.txt ") 5 >>> for line in nf: 6... print line7... 8 This is a new file.
1 >>> with open ("G: \ pythonWorkspace \ python \ study \ test.txt", "a") as fp: # with open can also create a file to open the file, applicable to close () after with open write can not be written, it will automatically process 2... fp. write ("\ n what's your name? ") 3... 4 5 >>> f = open ("G: \ pythonWorkspace \ python \ study \ test.txt") 6 >>> for line in f: 7... print line 8... 9 10 11 what's your name? 12 >>>

Different file reading methods

1 >>> help (file. read) 2 Help on method_descriptor:
# The parameter size is optional. If there is no parameter, all content of the file is read. If there is a parameter, it is read to the specified byte, then, the read content is returned in the form of a string. The 3 read content is returned to the memory at a time, which is convenient and quick. In this way, if the file size is very large, the memory overhead will be too large. 4 read (...) 5 read ([size])-> read at most size bytes, returned as a string. 6 7 If the size argument is negative or omitted, read until EOF is reached. 8 Notice that when in non-blocking mode, less data than what was requested 9 may be returned, even if no size parameter was given.10 11 >>> help (file. readline) 12 Help on method_descriptor Finally, return an empty string to the end of the file. End of file (EOF) 14 readline (...) 15 readline ([size])-> next line from the file, as a string.16 17 Retain newline. A non-negative size argument limits the maximum18 number of bytes to return (an incomplete line may be returned then ). 19 Return an empty string at EOF.20 21 >>> help (file. readlines) 22 Help on method_descriptor: 23 returns a list of behavior units, which is equivalent to executing readline to get each row. Then, the string of this row is used as an element in the list, put it in a list and return the list. 24 readlines (...) 25 readlines ([size])-> list of strings, each a line from the file.26 27 Call readline () repeatedly and return a list of the lines so read.28 The optional size argument, if given, is an approximate bound on the29 total number of bytes in the lines returned.

Example: read an object

Read () reads the file content. If a parameter is specified, the corresponding content of the specified byte is returned. If no parameter is specified, all the file content is returned.

Readline () reads a file in the unit of action, returns a string, reads a row each time, and reads it cyclically. If no parameter is specified, it is read to the end of the file.

Readlines () returns a list of behavior units. It is equivalent to executing readline to get each row. Then, the string of this row is used as the list element and the list is returned.

Import fileinput

F. seek (0) changes the location of the current file

F. tell () tells the current pointer position of the file, the current position in the file

1 >>> f = open ("G: \ pythonWorkspace \ python \ study \ test.txt") 2 >>> c = f. read () # read all the content of the file and put it in a variable 3> c 4 "\ n what's your name? "5 >>> f = open (" G: \ pythonWorkspace \ python \ study \ test.txt ") 6 >>> f. read (5) # if there is a parameter, the corresponding byte content 7' \ n wha' 8 >>> f = open ("G: \ pythonWorkspace \ python \ study \ test.txt ") 9 >>> f. readline () returns the content of the first line. Each line is a string 10' \ n' 11 >>> f = open ("G: \ pythonWorkspace \ python \ study \ test.txt ") 12 >>> f. readlines () returns a list. Each row in the list is an element 13 ['\ n', "what's your name? "] 14 >>> import fileinput # introduce a large file module to avoid the problem that the file is too large and the memory is too full. 15 >>> for line in fileinput. input ("G :\\ pythonWorkspace \ python \ study \ bigfile.txt"): 16... print line17... 18 Before getting started, 19 20 you may want to find out which IDEs and text editors are tailored to make Python editing easy, 21 22 browse the list of introductory books, 23 24 or look at code samples that you might find limit 26 There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page.27 28 There is also a list of resources in other ages which might be useful if English is not your first when age.29 >>> f = open ("G: \ pythonWorkspace \ python \ study \ bigfile2.txt ") 30 >>> for line in f: 31... print line32... 33 Before getting started, 34 35 you may want to find out which IDEs and text editors are tailored to make Python editing easy, 36 37 browse the list of introductory books, 38 39 or look at code samples that you might find yourself 41 There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page.42 43 There is also a list of resources in other ages which might be useful if English is not your first language.
# After reading a file, you need to open the file again. The reason is that the pointer has been moved to the end of the file. 44 >>> f. seek (0) # Use seek () to move the pointer. The parameter 0 is used to return the pointer to the beginning of the file, 45 >>> f. readline () 46 'before getting started, \ n' 47 >>> f. tell () # Use tell () to view the position of the current pointer 48 26L49 >>> f. seek (4) # The parameter is 4. the pointer is located at the end of the position from the beginning to 4th characters, 50 >>> f. tell () 51 4L52 >>>

 

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.