Python Basic file operations

Source: Internet
Author: User

File mode

' R ' Read mode
' W ' Write mode
A Append mode
' B ' Binary mode
+ Read/write mode

Attention:
' B ': Binary mode can be added to other modes using

' + ': Read/write mode can be added to other modes of use

Several concepts:
Why use binary mode? :
We all know that data is stored in binary form, such as text and images.

There is a problem with different line breaks in the operating system, for example, the specification in UNIX is \ n means the end line is another line, but in Windows it is \ r \ n.

If you open the file as text in Python, Python will do some automatic processing, which will be the interchange of \ r \ n, but this would destroy the binary data.

So we open the file in binary form when we need to protect the raw data.

The concept of a buffer:
The third parameter in the File Open function (open) controls the size of the buffer (the absolute value can be taken because the parameter can be positively negative).

What is the buffer zone?

Even if you use memory instead of a hard drive to make the program faster, the updated data will not be written back to the hard disk without a special function call (Close () or flush ()).

  

Why to close a file:

Because of the presence of buffers, the meaning of closing a file is understandable, in order to make the changed data write back to the hard disk.

Of course, you can not manually close the file, because the program will automatically close the file after execution, but this is a habit problem, good habits will always be useful for a lifetime.

Several basic functions of file operations:

Read (n) Read [Specify] string
ReadLine () Read a row
ReadLines () Read all rows, return values to a list
Write () Write Data
Writelines () Write a list
Seek () Redirect, reassign the file pointer (concept in C language)
Tell () Returns the current file pointer position

Attention:
There may be some formal parameters I did not label, but the function is at a glance.

File iterators

One character read file for one character: (using read ())

1 f = open ('20160608.txt','r')2 char = F.read (1)3 while char:4     print  ( char)5     char = f.read (1)

Read files on one line: (using ReadLine ()/ReadLines ()/Fileinput)

ReadLine ()

 1  f = open ( " 20160608.txt   ", "  r    )  2  line =  F.readline ()  3   Line:  4  line  = line . Strip ()  5  print   (line )  6  line  = F.readline () 

Attention:

Because the returned line has ' \ n ' so that he is treated with an empty (strip ())

ReadLines ()

1 f = open ('20160608.txt','r')2 lines = f.readlines ()3 for in lines:4      Print (Line.strip ())

Fileinput

1 Import Fileinput 2  for  in Fileinput.input ('20160608.txt'):3     Print (Line.strip ())

Is the file iteration more simple? Yes!

1 f = open ('20160608.txt','r')2  for inch F: 3     Print (X.strip ())

After python2.2, the file objects are iterative. This shows the elegance of Python.

At last

Remember used to write a CPP to calculate the number of two files in addition to the program, this time with Python write to try to write a thief rotten, or a C + + ideas, just a simple function of a lot of

1 deftonumberlist (L):2NEWL = []3      forLinchL:4          forXinchL.split (' '):5 newl.append (x)6     returnNEWL7#将读取的列表转为元素都是一个一个元素的列表8 Try:9data1 = open ('Data1.txt','R')Tendata2 = open ('Data2.txt','R') OneData1list =data1.readlines (); AData2list =data2.readlines (); -Newdata1 =tonumberlist (data1list) -NEWDATA2 =tonumberlist (data2list) the  -      forIinchRange (len (newdata1)): -         Print(int (newdata1[i]) +Int (newdata2[i])) -      + finally: - data1.close () +Data2.close ()

Data1 DATA2 Calculation results

Python Basic file operations

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.