python--Files and Streams

Source: Internet
Author: User
Tags pprint

1. How to open a file

The open function is used for opening the file with the following syntax:

Open (Name[,mode[,buffering]])

Open (' Test.txt '. R)

The open function uses a file name as the only mandatory argument, and then returns one of the document objects. Both the mode and buffer (buffering) parameters are optional.

The following describes the mode and buffer functions of the Open function

1.1 File Mode

' R ': Read mode

' W ': Write mode

' A ': Append mode

' B ': binary mode

' + ': Read/write mode

The ' B ' mode changes the way the file is processed. For processing some other type of file (binary), such as a sound clip or image, you should add ' B ' to the pattern parameter. The parameter ' RB ' can be used to read a binary file.

1.2 Buffering

The 3rd parameter of the Open function (optional) controls the buffering of the file. If the parameter is 0 (or false), the I/O (input/output stream) is unbuffered (all read and write operations are for the hard disk), and if 1 (or true),

I/O is buffered (meaning Python uses memory instead of the hard drive, making the program faster and only using flush or close to update the data on the hard drive). Numbers greater than 1 represent the size of the buffer (in bytes), 1

(or any negative number) represents the use of the default buffer size.

2. Basic file Methods

The way to open a file has been introduced, so the next step is to use them to do something useful. The next step is to introduce some basic methods for file objects (and some class file objects, sometimes called streams).

2.1 Reading and writing

The most important ability of a file (or stream) is to provide or receive data. If you have a class file object with the name F, you can write and read the data using the F.write method and the F.read method (in string form).

Each time a f.write (string) is called, the supplied argument string is appended to the existing part of the file

f = open ("somefile.txt""w") f.write ('   ') f.write ('python! ' ) f.close ()-------- results: hello,python! 

Reading a file is simple, just remember to tell the stream how many characters (bytes) to read.

As follows:

1f = open ("Somefile.txt","R")2Print (F.read (4))3 print (F.read ())4 f.close ()6------------7 Results:8D:\Python27\python.exe d:/pythonwork/test01/file_1.py9 HellTenO, python!

Note: You can omit the schema description when calling open, because ' R ' is the default.

* * Random Access

The above examples use the file as a stream, which means that the data can only be read sequentially from beginning to end. In fact, it is also possible to move the read file location freely in a file, using the method of the class file object, seek and tell, to directly access the part of interest (this method is called random access).

Seek (Offset[,whence]): This method moves the current position (where it is read and written) to the location defined by Offest and whence. The offset class is a byte (character) number that represents the offset. Whence default is 0, which means that the offset is calculated from the beginning of the file (the offset must be non-negative). Whence may be set to 1 (moves relative to the current position, at which point offset can be negative) or 2 (as opposed to the end of the file)

Examples are as follows:

f = open ("Somefile.txt","W") F.write ('0123456789') F.seek (5) F.write ("Hello, python!.") F.close () F= Open ("Somefile.txt","R") Print (F.read ())------------------------results: D:\Python27\python.exe D:/pythonwork/test01/File_1.py01234hello, Python!

The Tell method returns the location of the current file as shown in the following:

f = open ("somefile.txt""R") print (F.read (3  ) Print (F.read (2)) print (F.tell ())--------- Result: D:\Python27\python.exe D: /pythonwork/test01/file_1.py0125

Note: The number returned by the F.tell method is a long integer in this case. But not all of this is the case.

2.2 Read and Write lines

You can use File.readline to read a separate line. The ReadLine method can read all the rows in a file and return them as a list.

The WriteLine method and the ReadLine method are reversed: A list of strings is passed to it (actually any sequence or iteration of the object), which writes all the strings to the file (or stream). Note that the program does not add new lines and needs to be added yourself.

Note: On a platform that uses other symbols as line breaks, use \ r (MAC) and \ r \ n (Windows) instead of \ n.

2.3 Closing files

You should remember to close the file using the Close method.

There is actually a statement specifically designed for this case, the WITH statement:

With open ("Somefile.txt") as Somefile:

Do_something (Somefile)

The WITH statement can open a file and assign it to a variable (somefile), which can then be written to the file in the statement (or perform other operations). The file is automatically closed after the statement ends, even if the end is caused by an exception.

Context Manager

The WITH statement is actually a very general structure that allows the use of the so-called context manager. The context manager is an object that supports both _enter_ and _exit_ methods.

The _enter_ method is called without parameters and is invoked when it enters the WITH statement block, and the return value is bound to the variable following the AS keyword.

2.4 Using the Basic file method
1 ImportPprint2 3 4With open ("Somefile.txt") as Somefile:5S1 = Somefile.read (7)6      Print(S1)7S2 = Somefile.read (4)8      Print(S2)9 Ten  OneWith open ("Somefile.txt") as Somefile: AS3 =Somefile.read () -      Print(S3) -  the  -With open ("Somefile.txt") as Somefile: -       forIinchRange (3):#Cycle three times -          Print('%s:%s'%(str (i), Somefile.readline (). Strip ())) +  -  + Print(Pprint.pprint (Open ("Somefile.txt"). ReadLines ())) A  at  - #Write a file -With open ("Somefile.txt","W") as Somefile: -Somefile.write ("This\nis No\nhaiku")

Results:
D:\Python27\python.exe d:/pythonwork/test01/flie_2.py
This
Is
No

This
is no
Haiku
0:this
1:is No
2:haiku
[' this\n ', ' is no\n ', ' Haiku ']
None

Modify a text file case

1 with open ("somefile.txt""r+") as Somefile:  2      lines = somefile.readlines ()3      "isn ' t b\n " 4      Somefile.writelines (lines)
3. Iterate over the contents of the file by byte 3.1

The most common way to iterate over the contents of a file is to use the Read method in a while loop. Here's an example:

1 #define an expression function2 defprocess (String):3     Print("Processing:", String)4 5 6With open ("Somefile.txt","R") as Somefile:7char = Somefile.read (1)8      whileChar:9 process (char)Tenchar = Somefile.read (1)

As you can see, the assignment Statement char =f.read (1) is used repeatedly, and code duplication is often considered a bad thing. To avoid this situation, you can use the while True/break statement.

1 with open ("somefile.txt""R") as Somefile:  2while       True:3         char = somefile.read (1)4          If not char:5break              6         Process (char)
3.2 Action by row

Using ReadLine in while

1 with open ("somefile.txt""R") as Somefile:  2while       True:3Line         = somefile.readline (). Strip ()  4         if not line :5break             6          Process (line)

Iterate rows with ReadLines

1 with open ("somefile.txt""R") as Somefile:  2for in       somefile.readlines ():3         process ( Line.strip ())
3.3 Using Fileinput to implement lazy line iterations
1  for  in Fileinput.input ("somefile.txt"):2     process (line)
3.4 File Iterators

Iterate over files without using variables to store file objects

1  for  in open ("somefile.txt"):2     process (line)

You can perform the same actions on a file iterator as an ordinary iterator. As follows:

1With open ("Somefile2.txt",'r+') as Somefile:2Somefile.write ('First line\n')3Somefile.write ('Second line\n')4Somefile.write ('Third line\n')5Lines =Somefile6     Print(lines)7 8 #Convert the contents of a file to a list9lines = List (open ("Somefile2.txt"))Ten Print(lines) One  AFirst, second, third = open ("Somefile2.txt") - Print(first) - Print(second) the Print(third)

Results:
D:\Python27\python.exe d:/pythonwork/test01/flie_2.py
[' First line\n ', ' Second line\n ', ' third line\n ']
First line

Second Line

Third line

In this case, it is important to note the following points.

    • Use Print to write content to the file, which adds a new line after the supplied string.
    • Using a sequence to unpack an open file, put each row in a separate variable (this is very useful because you don't generally know how many rows are in the file, but it shows the "iteration" of the file object)
    • The file is closed after the file is written to ensure that the data is updated to the hard disk. using with open (filename) as filename is recommended:

  

  

python--Files and Streams

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.