Python Basic Tutorial Summary 10--file

Source: Internet
Author: User
Tags stdin pprint

1. Open File

Open (name[mode[,buffing]) parameters: file, mode, buffer

1) Name: is mandatory option, mode and buffer are optional

#如果文件不在, the following error will be reported
1 >>> f = open (R'D:\text.txt','r') 2Traceback (most recent): 3 "<stdin> " in <module> 4or'd:\\text.txt '

2) file mode

' R '        Read mode ' w'     write mode ' a  '     append mode   '  b' binary     mode (can be added to other modes for use) '  +'    read/write mode (can be added to other modules for use)  

Note:

The default way, for example, open (' filename ') is read mode

r+, which means that the read-write

If it is a binary file or a graphics file, you must use buffer mode

Normal W mode overwrites the contents of the file, and a mode does not.

RB can be used to read binary files.

Using the U parameter in the parameter mode allows you to use a common line feed support mode when opening a file, regardless of the \r,\n\r, instead of running the platform.

3) buffering

0 or false: No buffering, all operations are directed to the hard drive

1 or true: There is buffering, memory instead of hard disk, fast, only close,flush to write HDD sync.

> 1: Indicates the size of the buffer

-1: Indicates the default buffer size

2. File methods

2.1 Reading and writing

#对空文件来说: When a write is provided, it is appended at the end of the string.

1>>> f = open ('Somefile.txt','W')  2>>> F.write ('Hello,')  3>>> F.write ('world!')  4>>>f.close ()5 #somefile.txt File Contents6hello,world!

#对于非空文件: When the W method is supplied, the contents of the file are overwritten

1>>> f = open ('Somefile','W')  2>>> F.write ('This is 1st line.\n')  3>>> F.write ('This is a 2nd line.')  4>>>f.close ()5 #somefile.txt File Contents6This is1st line. 7This is2nd line.

Examples of simple reads:

1>>> f = open ('Somefile.txt','R')  2>>> F.read (16)#read 16 characters First3 'This was 1st line'  4>>> F.read ()#will read the remainder unless seek locates to 0 and re-reads5 '. \nthis is 2nd line.'  6>>> F.close ()

2.2 Pipe Output

$ Cat Somefile.txt | Python somescript.py | Sort

#一个简单例子: Count the number of words in a text

$ cat Somefile.txt This is  a book! That's a dog! Who is?

Script Checklist:

#somescript. py  Import sys  text  = Sys.stdin.read ()    #读取所以输入words = Text.split ()        #分割字符串   Print "Word Count:", Len (words)  

Output Result:

# Cat Somefile.txt | Python somescript.py  Word count:11  

  

2.3 Read and Write lines

ReadLine:  read lines, including newline characters ReadLines:  Read all lines write:      Note: There is no WriteLine method writelines: Write Multiple lines

Note: How can I tell what the different lines end up with? Os.linesep

#UNIX   >>> import os  >>> os.linesep  ' \ n '  #WINDOWS  >>> import os  >>> os.linesep  ' \ r \ n '  

  

2.4 Basic File methods

#测试文本somefile. txt

Welcome to this filethere are nothing here exceptthis stupid haiku

#首先读取指定字符--f.read (N)

>>> f = open (R ' d:\Learn\Python\somefile.txt ')  >>> f.read (7)  ' Welcome '  >>> F.read (4)  ' to '  >>> f.close ()  

#其次读取所有的行--f.read ()

>>> f = open (R ' D:\Learn\Python\somefile.txt ', ' R ')  >>> print f.read () Welcome to the This  file There is nothing here  except  This stupid haiku  

#接着是读取行--f.readline ()

>>> f.close ()  >>> f = open (R ' d:\Learn\Python\somefile.txt ')  >>> for I in range (3) :  ...     Print str (i) + ': ' + f.readline () ...  0:welcome to this file 1:there are nothing here  except  2:this stupid haiku  

#再读取所有行--f.readlines ()

>>> import pprint  >>> pprint.pprint (open (' Somefile.txt '). ReadLines ())  [' Welcome to this file\n ',   ' There is nothing here except\n ',   ' this stupid haiku ']  

#下面是写文件--f.write (' ... ')

>>> f = open (R ' Somefile.txt ', ' W ')  >>> f.write (' This\nis no\nhaiku ')  >>> f.close ()  after running the file, the contents are as follows: This is  no  haiku  

# finally the Writelines--f.writelines (' .... ')

>>> f = open (R ' somefile.txt ')  >>> lines = F.readlines ()  >>> f.close ()  > >> lines[1] = "isn ' t a\n"  >>> f = open (' Somefile.txt ', ' W ')  >>> f.writelines (lines) C18/>>>> F.close ()  after running, the file contents are as follows: This   isn ' t a  haiku  

2.5 Closing files

Always remember close () to close the file, for the purpose of doing so:

Security considerations to prevent files from collapsing for some reason and not to write data

Close () to write data to the hard disk for data synchronization considerations

For efficiency reasons, the data in memory can be emptied partially.

To ensure close () at the end of the program, it can be used in conjunction with try/finally

# Open your file here  try:      # Write data to your file  finally:      file.close ()  

Note: The general file is written to the hard disk after close (), and if you want to see what is written without executing the close () method, flush will come in handy.

3. Iterating over the contents of the file

3.1 Processing by byte

def process (string):          print ' processing ... ', string  f = open (' Somefile.txt ') while  True:          char = F.read (1)          If not char:                  break          process (char)  f.close ()  

3.2 Row-by-line processing

f = open (filename) while  True: line      = F.readline ()      If the line: Break      Process (line)  F.close ()  

3.3 Read All content

If the file is not very large, you can use Read (), or readlines () to read the content as a string to handle.

#用read来迭代每个字符

f = open (R ' D:\Work\Python\somefile.txt ') for  Char in F.read ():      process (char)   f.close ()

#用readlines来迭代行

f = open (R ' D:\Work\Python\somefile.txt ', ' r ') for line in   F.readlines ():      process (line)  F.close ()  

3.4 Using Fileinput lazy Iteration

  When you need to iterate over a large file, ReadLines consumes too much memory. This time you can use the while loop and the ReadLine method instead.

Import Fileinput    def process (string):      print ' processing ... ', string for line in  fileinput.input (' Somefile.txt '):      

  

3.5 File Iterators

#Python中文件是可以迭代的

f = open (' somefile.txt ')  for line in F:      print line,  f.close ()  

#如果希望Python来完成关闭的动作, the code can be more streamlined by iterating over the file without using variables to store variables

For on open (' Somefile.txt '):      print Line,  

#sys. StdIn can also be iterated

Import sys  for line in Sys.stdin:      print line,  run result:  D:\work\python>python file.py  # Enter the following two lines  hello,world!  hello,jerry!  ^z        #按下CTRL The +z key, the input content is displayed  hello,world!  hello,jerry!  

#可以对文件迭代器执行和普通迭代器相同的操作. For example, they are converted to a list of strings, which achieves the same effect as using ReadLines.

>>> f = open (' Somefile.txt ', ' W ')  >>> f.write (' first line\n ')  >>> f.write (' Second line\n ')  >>> f.write (' third line\n ')  >>> f.close ()  >>> lines = list (open (' Somefile.txt ')  >>> lines  [' First line\n ', ' Second line\n ', ' third line\n ']  >>> First, Second,third = open (' somefile.txt ')  >>> first  ' first line\n '  >>> second  ' second Line\n '  >>> third  ' third line\n '  

  

Python Basic Tutorial Summary 10--file

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.