Python Learning (vi)--iterative, file read-write __python

Source: Internet
Author: User
Tags iterable readline

iterations
Iteration through for...in ... Realize
①list

>>> l=[' Ryan ', ' Rick ', ' Morty ']
>>> for key in L:
    print key


Ryan
Rick
Morty

②tuple

>>> t= (' Ryan ', ' Rick ', ' Morty ')
>>> for key in T:
    print key


Ryan
Rick
Morty

③ string

>>> for K in ' abcdefgh ':
    print K


a
b
c
d
e
f
g
h

④ Dictionary
(Dict storage order is not listed in list order)
Iteration Key:

>>> d={' name01 ': ' Ryan ', ' name02 ': ' Rick ', ' name03 ': ' Morty '}
>>> for key in D:
    print key


name03
name02
name01

Iteration Value:

>>> d={' name01 ': ' Ryan ', ' name02 ': ' Rick ', ' name03 ': ' Morty '}
>>> for value in D.iteritems ():
    Print Value


(' name03 ', ' Morty ')
(' Name02 ', ' Rick ')
(' name01 ', ' Ryan ')

Iterate key and value at the same time:

>>> for Key,value in D.iteritems ():
    print key,value


name03 Morty name02
Rick
name01 Ryan

⑤ simultaneously iterate over multiple variables:

>>> for X,y,z in [(' A ', 1,4), (' B ', 4,8), (' d ', 7,9), (' s ', 5,89)]:
    print x,y,z


a 1 4
B 4 8
D 7 9
s 5 89

⑥ uses the enumerate function to turn a list into an index-element pair:

>>> l=[12,56,789,15,5,89,45,34]
>>> for i,v in Enumerate (L):
    print i,v


0
1 56< C13/>2 789
3
4 5 5 [6] 7
34

⑦ determines whether an object can be iterated:

>>> from collections import iterable
>>> isinstance (' Ryan ', iterable)
True
>> > isinstance (12345,iterable)
False

file read and write

1 open () function
flie_obj = open (filename, mode= ' r ', buffering =-1)

FileName is the incoming filename
Mode is an optional parameter, the default value is R, (' R ' Read, ' W ' Write, ' RB ' read binary file < image, video, etc., ' WB ' writes binary file)
Buffering the default value is-1 (for system default caching), optional parameters (0 means no cache, 1 or greater than 1 for caching a row or a specified buffer size)

>>> f1=open (' F:/data.txt ', ' R ')
>>> print f1.read ()
hello,world!
>>> F1.close ()
>>> f2=open (' F:/data.txt ', ' W ')
>>> f2.write (' ABCDEFG ')
>>> f2.close ()

When reading a non-ASCII text file, you must open it in binary mode and then decode it. such as GBK encoded files:

F=open (' F:/data.txt ', ' R ')
U=f.read (). Decode (' GBK ')
print U
f.close ()

(The contents of the Data.txt file are Chinese)
Or use the Codecs module:

Import codecs
with Codecs.open (' F:/data.txt ', ' r ', ' GBK ') as F:
    print F.read ()

2 ReadLines () function
File_obj.readlines ()
Reads data from a line in a file and returns a list containing line breaks.

3 ReadLine () function
File_obj.readline ()
Reads the first row of data in the file, returning a string;

4 Seek () function
File_obj.seek (Offet, whence=0)
Move the file pointer in the file, from whence (0 for the head of the file, 1 for the current position, and 2 for the tail of the file) to offset bytes;
The whence parameter is optional, and the default value is 0.

5 Split () function
Split (self, sep=none, Maxsplit=none)
Split () function: Specifies the delimiter to split the string, parameter 1 is the specified delimiter, and parameter 2 is the number of separated strings;

s = "40920  8.326976    0.953952    8.326976    0.953952"
print s.split (' \ t ')
print s.split (' t '), 2)

Output:

[' 40920 ', ' 8.326976 ', ' 0.953952 ', ' the ' o ', ' 8.326976 ', ' 0.953952 ']
[' 40920 ', ' 8.326976 ', ' 0.953952\t320\t8.326976\t0.953952 ']

6 strip () function
Intercept all carriage return characters.

file Shutdown

Use try...finally to ensure that files are closed correctly, regardless of error

Try:
    f=open (' F:/data.txt ', ' R ')
    print f.read ()
finally:
    if f:
        F.close ()

Or use the WITH statement:

With open (' F:/data.txt ', ' R ') as F:
    print F.read ()

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.