Python Basic Learning 3-file read/write, collection, JSON, functions

Source: Internet
Author: User

1 file reading and writing supplement

File modification

Method 1: Simple Rude Direct:

1. Get all the contents of the file first

2. Then modify the contents of the file

3. Empty the contents of the original file

4. Re-write

f = open (' test1.txt ',' r+ ')
F.seek (0)
All_data = F.read ()
New_data = all_data.replace (' 123 ',' python ')
F.seek (0) # Move the pointer to the front
F.truncate () # Empty the original file contents
F.write (New_data) # re-write file contents
F.flush ()
F.close ()

Method 2: Efficient processing

1. Open the original file first, then open an empty file

2, loop processing the original file in each row of data, processed and then write to the new file

3, delete the original file, the name of the new file changed to the original file name

ImportOs
withOpen' Words.txt ') asFr,open (' WORDS1 ',' W ') asFw:
forLineinchFr
line = Line.lstrip ()#Remove the left space
ifLine#determine if the row has data
line = Line.replace ('You're',' You ')#Replace Data
Fw.write (line)#write to the new file
Os.remove (' Words.txt ')#Delete the original file
Os.rename (' WORDS1 ',' Words.txt ')#Rename the new file to its original file name

Opening a file using the with open method will automatically close without having to manually close the file;

f = open (' note . txt ') # opened file is called a file handle or file object

for lines in F: # Direct Loop file object, each time the loop is to go to each row of data
print ("line", line)

2 Collection, JSON module

Set Effect:

1, natural to go heavy

2. Relationship test-intersection, difference set, set, inverse difference set, symmetric difference set

Nums = [1,2,3,2,3,4,1,5,6]
Print (Set (nums))

List = [1,2,3,4,5,3,6]#List
List_dict = {2,3,4,3}
List_2 = [2,3,5,7,8]
List = set (list)#convert a list to a collection
List_2 = Set (list_2)
Print'intersection:', List.intersection (list_2))#intersection, remove duplicate data
Print (List & list_2)#This is also called intersection .

Print'and set:', List.union (list_2))#Union, to re-unify the show
Print (List | list_2)#This is also called the set

Print'difference set:', List.difference (list_2))#difference Set, removeListin some,list_2not in the
Print (list-list_2)#This is also called the difference set

List_3 = Set ([1,3,6])
Print'subset:', List_3.issubset (list))#subset,List_3the value inListall, returns the result of a Boolean type
Print'Parent Set:', List.issuperset (List_3))#Parent Set

Print'symmetric difference set:', List.symmetric_difference (list_2))#symmetric difference sets, theListand thelist_2The values in each other are removed, and the two collection
Print (list ^ list_2)#This is also called the symmetric difference set .


#
Collection Operations
List.add (123)#You can add only one
Print (list)

List.update ([888,999])#You can add multiple
Print (list)

List.remove (999)#Delete the specified element
Print (list)

List.pop ()#Random Delete
Print (list)

List.discard ()#Deleting a non-existent element does not error
Print (list)

Instance:

# Monitoring Logs
#1
, if an IP is accessed more than three times within a minute
#2
, just Find out his IP,split, take the first element .
#3
, find out all the IPs, count the numbers
#4
, judge each IP number is greater than , send mail
#5
, log the file pointer to the next read
#6
, wait 60s, re-read the file

Import Time
Point = 0 # stores the initial location of the file

While True:
withOpen' Access.log ') asF:
F.seek (Point)
Ip_info = {}#StoreIPand the number of times it appears
forLineinchF:
ip = line.split () [0]
ifIpinchIp_info:
#ip_info [IP] = Ip_info[ip] + 1
IP_INFO[IP] + = 1
Else:
IP_INFO[IP] = 1
Point =f.tell ()#gets the position of the current file pointer
forKinchIp_info:
offIp_info.get (k) >= 100:
Print'theIPis attacking you .%s '%k
Time.sleep (#等待60s)

JSON is a string, but long like a dictionary;

In JSON there are only double quotes, no single quotes;

import json
User_info = "'                       
{"test1": "123456", " Test2 ":" 123456 "}    
"
user_dic =json.loads (user_info)          # convert json String (string) to dictionary
Print (user_dic)
Print (' User_info ', type (user_info))
Print (' User_dic ', type (user_dic))

stu_info = { ' Zhangsan ' : { ' cars ' : [ ' BMW ' , ' Ben-z ' ]}}
Stu_str = Json.dumps ( Stu_info)       # convert dictionary to json string
Print ( ' stu_str ' , type (STU_STR))
Print (STU_STR)
F = open ( ' stu.txt ' , ' W ' )
F.write (stu_str)
F.close ()

f = open (' Stu.json ', ' W ')
Json.dump (stu_info,f,indent=4) #不需要自己在write, people will help you write to the file, followed by the indent=4 to help you automatically indent, 4 means indent 4 characters

3 functions

1, function is a function, a method, simplify the code

2. function must be called before execution

3. A function to do only one thing

4, duplicate code is low-level

5, achieve the same function, the less code the better

defSay (name):#the function name, in parentheses the parameter is the formal parameter (the formal argument is the variable)
Print'%s hahaha '%name)#function Body
Say' Zhangshan ')#The parentheses in the function name are called the functions above, the arguments inside the parentheses are the arguments (actual arguments)



defSay1 (name,sex='male'):#the function name, in parentheses the parameter is the formal parameter (the formal argument is the variable)
#
required parameters, such asName
#
default value parameter, not required, assex= 'male'
Print'%s hahahaSex%s '% (Name,sex))#function Body
Say1 (' Zhangshan ')#The parentheses in the function name are called the functions above, the arguments inside the parentheses are the arguments (actual arguments)

The variables inside the function are local variables, which can only be used inside the function, and the function execution ends without the variable;

return value, if need to use the function of the result of the processing, write return, do not need, then do not write, if the function inside the return, function immediately end;

# function immediately ends Def calc (A, B):

res = A * b

Print (RES)

Return res #没有return返回时, the data type returned by the function is Nonetype, and the type of return is the result type of the function.

Cur_money = 8000

NX =calc (1000,13)

Print (Nx+cur_money)

Defmy ():

For I in range (100)

if i = = 2:

Return

Print (my ())

#Write a program that verifies whether the input string is a decimal
#
Ideas:
# 1
,0.12 1.23-12.3only one decimal point, the number of decimal points to determine;
# 2
, positive decimals, the left and right of the decimal point is an integer, only legal, through the separator to Judge
#3
, negative decimals, an integer to the right of the decimal point, and the left must be"-"start with only one minus sign;
#-5.4
#['-5 ', ' 4 ']
#[1:]
defCheck_float (s):
s = str (s)
ifS.count ('. ') = = 1:
S_list = S.split ('. ')
#5.3after the split is[5,3]

left = S_list[0]#left of decimal point
Rigth = s_list[1]#right of decimal point
ifLeft.isdigit () andRigth.isdigit ():
return True
Elif
Left.startswith ('-') andLeft.count ('-') ==1 andLeft[1:].isdigit () andRigth.isdigit ():#left. Count ('-') ==1This judgment is not to be written .
return True

Return False

Print (Check_float (1.8))
Print (Check_float (-2.4))
Print (Check_float ('-s.5 '))
Print (Check_float (' 50.232SS '))
Print (Check_float ( -3-4.4-9))


defMy_file (name,content=None):
withOpen (name,' A + ') asF:
F.seek (0)
ifContent
F.write (content)
Else:
returnF.read ()

Python Basic Learning 3-file read/write, collection, JSON, functions

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.