Python file processing

Source: Internet
Author: User
Tags readable throw exception

Variable = open (r ' file path) ', ' r[Open file mode] ', encoding= ' utf-8 text character set [default is Unicode]
Win needs to add R to the path, the character set and the file write format.

(1). The mode of opening the file has (default is text mode [test]):
R, read-only mode "default mode, file must exist, not present, throw exception"
W, write-only mode "unreadable; not exist" created; empty content "
A, append only write mode "unreadable; not exist" create; append content only "

(2). For non-text files, we can only use B mode, "B" means to operate in bytes (and all files are stored in bytes, using this mode regardless of the text file character encoding, image file JGP format, video file avi format)
Rb
Wb
Ab
Note: When opened in B, the content read is a byte type, and a byte type is required for writing, and encoding cannot be specified

(3), ' + ' mode (adds a function)
r+, read-write "readable, writable"---file must exist
w+, write read "writable, readable"---file does not exist, create directly
A +, write read "writable, readable"

(4) Read-write, write-read, write-read mode for bytes type operation
R+b, read and write "readable, writable"
W+b, write read "writable, readable"
A+b, write read "writable, readable"

2. How to Operate
Read
1. When the file is opened in text mode, the representation reads 3 characters
2. When the file is opened in B mode, the delegate reads 3 bytes
The rest of the files within the cursor movement are in bytes such as: seek,tell,truncate
Attention:
1. Seek has three modes of movement 0,1,2, of which 1 and 2 must be performed in B mode, but regardless of which mode is moved in bytes units
2. Truncate is a truncated file, so the file must be opened in a way that can be written, but not with W or w+, etc., because the file is directly emptied, so truncate to r+ or a or a + and other modes to test the effect. (First clear, in writing)

Write
W--Pattern write cursor starts from scratch, clears first, writes

Writable ()---Determine if the file is writable--true/false
Instance:
F=open (R ' a.txt ', ' W ', encoding= ' utf-8 ')
Print (F.writable ())
F.close ()

True

 write ()  ---Direct write, default append last, each time is from the beginning in the
  instance:
 f=open (R ' a.txt ', ' W ', encoding= ' utf-8 ')
 # print (f.writable ())
 f.write (' 1111\n ')
 f.close ()
 1111
 
  Writelines ()  ---can be list, meta-ancestor, dictionary way to write
 f=open (R ' a.txt ', ' W ', encoding= ' utf-8 ')
 f.writelines ([' 3333\n ', ' 44444\n '])
 f.close ()  
 3333
 44444
 
 a---Schema append file does not exist and is created, File exists then immediately after opening the file, move the cursor to the last.
 
 r---Read mode, the file must exist
 
 read. ()---files are all read in memory, recommended small files
 
 readlines ()  ---Files are all read in memory, but are displayed in the list
 
 readline (), end= '---read one line at a time, with a newline character by default, plus end= ' specify null
 
  Cycle Printing:
 with open (' B.txt ', ' R ', encoding= ' utf-8 ') sa f: #f specify variable name
  for i in F:
    print (i)
   
 b---bytes binary read, cannot specify character encoding, decode text Format Plus. Decode (' Utf-8 ')
  With open (' b.txt ', ' RB ',) as F:
  print (F.read (). Decode (' Utf-8 '))

Python CP command:

The import function is used to dynamically load classes and functions
OS Module

Os.remove (PATH)
Deletes a file with path. If path is a folder, it will throw oserror; View the following rmdir () to remove a directory.

Os.rename (SRC, DST)
Rename a file or directory, from SRC to DST

Instance:
Import OS

With open (' A.txt ', ' R ', encoding= ' utf-8 ') as F, \
Open ('. A.txt.swap ', ' W ', encoding= ' Utf-8 ') as O:
# data = F.read ()
# O.write (Data.replace (' Alex ', ' Alex ')) #方法一: only for small files
For I in F:
Print (i)
O.write (I.replace (' Alex ', ' Alex '))
Os.remove (' A.txt ')
Os.rename ('. A.txt.swap ', ' a.txt ')


Replace (' old ', ' new ', ' replace no more than Max times (not all) ')

Split ()
Specifies the delimiter to slice the string, and if the parameter num has a specified value, only the NUM substring is delimited
Grammar
Split () method syntax:
Str.split (str= "", Num=string.count (str)).

Parameters
STR--the delimiter, which defaults to all null characters, including spaces, line breaks (\ n), tabs (\ t), and so on.
Num--the number of splits.

Instance
The following example shows how the split () function is used:
#!/usr/bin/python

str = "Line1-abcdef \nline2-abc \NLINE4-ABCD";
Print Str.split ();
Print Str.split (', 1);
The result of the above example output is as follows:
[' Line1-abcdef ', ' line2-abc ', ' LINE4-ABCD ']
[' Line1-abcdef ', ' \nline2-abc \NLINE4-ABCD ']

‘‘‘
1. File a.txt content: Each line content is the product name, the price, the number.
Apple 10 3
Tesla 100000 1
MAC 3000 2
Lenovo 30000 3
Chicken 10 3
Through the code, build it into this type of data:
[{' name ': ' Apple ', ' price ': Ten, ' Amount ': 3},{' name ': ' Tesla ', ' price ': 1000000, ' Amount ': 1} ...]
and calculate the total price.
‘‘‘


List_info = []

With open (R ' B.txt ', ' R ', encoding= ' utf-8 ') as F:
For I in F:
List = I.split ()
Print (list)
List_info.append ({' name ': list[0], ' price ': Int (list[1]), ' count ': Int (list[2])})
# money = List (the map (Lambda x:x[' price ']*x[' count '],list_info)
Money = map (lambda x:x[' price '] * x[' count '], List_info)
SS = SUM (Money)
Print (' Total consumption%d dollars '%ss)
Print (List_info)


2, there are the following documents:
‘‘‘
-------
Alex is the old boy Python initiator, creator.
Alex is actually a tranny.
Who says Alex is SB?
You guys are so funny, Alex, you can't hide the temperament of senior cock silk.
----------
Replace all Alex in the file with an uppercase SB.
‘‘‘

Import OS

With open (' A.txt ', ' R ', encoding= ' utf-8 ') as F, \
Open ('. A.txt.swap ', ' W ', encoding= ' Utf-8 ') as O:
# data = F.read ()
# O.write (Data.replace (' Alex ', ' Alex ')) #方法一: only for small files
For I in F:
Print (i)
O.write (I.replace (' Alex ', ' Alex '))
Os.remove (' A.txt ')
Os.rename ('. A.txt.swap ', ' a.txt ')

2. Control cursor Movement
Create a file: A.txt
Hello, Helli.

With open (' A.txt ', ' R ', encoding= ' utf-8 ') as F:
Data1=f.read ()
Print (DATA1)
Print (F.tell ()) #告诉光标在什么位置, the display is in bytes
#只有一种情况下光标以字符为单位: File opens in RT mode, read (3)
#方法一:
F.seek (0)

#方法二: F.seek (' Number of moves ', ' reference, default is 0 '),--only t mode, you can also use 0,1 and 2 cannot be
#有三种模式0, 0 (1 is the current position, 2 is at the end)--1 and 2 must be used in B mode
F.seek (0,0)

Tail-f Access.log

Truncate file:
Only use a mode, if you use W mode, empty directly

With open (' Access.log ', ' a ', encoding= ' utf-8 ') as F:
F.truncate (3) #没有0, 1, 2 all from the beginning.

Python file processing

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.