Python3 from zero single row 2_ file read/write

Source: Internet
Author: User
Tags readable

The file operation is actually the same as our daily processing files, first open the file, then the operation, finally save close, in Python is the three steps:

1, open the file to get the handle of the file, the handle is understood as this file
2. Manipulating files through file handles
3. Close the file

  The file operation has the following three modes:

R: Read mode "readable; not writable, not present" error
W: Write mode "unreadable, not present" create; Delete content "//Note: As long as the W mode is written, no matter what is followed, the file does not exist, the file is empty, and then the contents are emptied and then written.
A: Append mode "unreadable; not exist" create; append content only "//Note: Append content is at the last pointer position to start writing, so generally so, first F.seek (0), back to the first line of the first byte of the file position.

  Following the '+' sign after the pattern indicates that the file can be read and written:

r+: "Readable, writable, append, if the open file does not exist, will be an error"
w+: "Read-write mode, using w+, the existing file content will be emptied, you can read the contents of the written file"
A +: "Append read/write mode, create without existing, append content only;"

  Following 'b' after the pattern means processing the binary file: Rb,wb,ab

  1. Reading files

F=open ('a.txt','R', encoding='Utf-8')#you do not need to set the character type under the Mac, the operating system default character type is utf-8;windows need to set this character type, the system default is the GBK character typePrint(F.read ())#read the contents of the file, return a string, when the file is too large, do not recommend this operation, to prevent memory explosionPrint(F.readlines ())#read the contents of the file, return a List,list each element is a file of each linePrint(F.readline ())#Read only one row at a timef.close ()#The for loop file handle is looping through the contents of a file through a row, and the benefit is that when the file is too large, it prevents the memory from explodingF=open ('a.txt','R', encoding='Utf-8')Print(F.read ()) I=1 forContentinchF:Print('{line}: {content}'. Format (line=i,content=content)) I+=1f.close ()

  2. Writing files

F=open ('a.txt','W', encoding='Utf-8') F.write ('hahaha')#can only write a string, cannot be a listF.writelines (['AAA','BBB','CCC'])#it says list.F=open ('a.txt','r+', encoding='Utf-8')#r+ Read-write mode, as long as there is r permission in, when the file does not exist will be an errorF.write ('1111')#read-write mode, when writing the data will be written from the first line, replace the previous file in the first line of the contents of the top n characters (n is the length of the characters written)F=open ('a.txt','w+', encoding='Utf-8') F.write ('ASD') F.seek (0)#Seek (n), move pointer to n position, 0 firstPrint(F.read ())

  

  3. Append mode

  Append mode is similar to the above, note that: Append content is at the end of the pointer to start writing, so generally so, to first F.seek (0), back to the first line of the first byte of the position of the file, always pay attention to the position of the pointer.

F=open ('a.txt',' a+', encoding='utf-8 ' ) F.seek (0)print(F.read ()) I=1 for in F:      Print(' {line}: {content}'. Format (line=i,content=content))    I +=1f.close ()

  4.with Method Action File

  With the operation of the file, you can less close file closure method, this with will automatically close the file, do not need us to repeat the same, other usages.

With open ('a.txt','r') as F:    for inch F:         Print (line)

  

  5. File modification

  There is a detail, the daily modification of the file, when the file is opened, will produce a hidden file, in fact, we modify the content process is this: Open file--on the hidden file on the deleted file content--Save hidden files, before the file delete Hide file Rename start file name is such a process, then we want to modify the file when it is actually the same:

1. Read mode to open the file to be modified a
2. Modify what is read
3. Write the modified content into the new file B
4. Delete File a
5. rename File B to a

ImportOswith Open ('sunshine always after the rain .','R', encoding='Utf-8') as F1,open ('a.txt','W', encoding='Utf-8') as F2: forLineinchF1:new_line=line.replace ('Sunshine','Rainbow') F2.write (new_line) os.remove ('sunshine always after the rain .') Os.rename ('a.txt','sunshine always after the rain .')

  

Of course there is another way, do not need to delete files, directly empty files can be

F1=open (' Sunshine always after the storm', 'a+', encoding='utf-8  ') f1.seek (0) Res=f1.read () new_content=res.replace (' Rainbow ',' sunshine ') f1.seek (0) f1.truncate () f1.write (new_content) f1.close () 

  6. Collection

A collection is also a data type, a similar list of things, it is characterized by unordered, non-repeating, that is, the collection is no duplicate data, the role of the following:

1, it can be a list of duplicate data removed, and do not need you to write judgment
2, can do a relationship comparison, such as the intersection of mathematics, and set, etc.

The operations and lists of the collection are similar:

lis=[1,2,3,4,4,5,5,6,7,8,9]myset=set (LIS)  # This defines a set of print(myset)    # Remove Duplicate data, 4, 5, show only once Myset.add (888)# add Element # add value myset.remove (777) # Deleting an element if the element does not exist will cause an error Myset.pop ()# to delete a random element and return the deleted element Myset.discard ('  dddd')# If the deleted element exists, deleted, does not exist do not handle

Collection Operation methods:

Set1 = {1, 2, 3, 4, 5, 6, 7,8,9}set2= {1, 2, 3, 4, 6}set3= {1, 2}Print(Set1.intersection (Set2))#Take the intersection, that is, take Set1 and Set2.Print(Set1 & Set2)#Take intersectionPrint(Set1.union (Set2))#Take the union, that is, merge the Set1 and the Set2, and then remove the duplicatePrint(Set1 | set2)#Fetch and setPrint(Set1.difference (Set2))#The set of differences exists in the list, not in the Set2Print(Set1-Set2)Print(Set3.issubset (Set1))#determine if Set3 is a subset of Set1Print(Set1.issuperset (SET3))#determine if Set1 is Set3 's parent setPrint(Set1.isdisjoint (SET3))#determine if Set1 and Set3 have intersectionPrint(Set1.symmetric_difference (Set2))#symmetric difference set, output a value that is not in the two list, that is, the same in the two set to removePrint(Set1 ^ set2)

   

 7. Write a monitor server script, run every minute, in this minute if the number of IP access more than 200, it is counted into the blacklist.

The log file format is as follows:

58.19.57.99--[04/jun/2017:05:23:30 +0800] "get/http/1.0" 302 161 "-" "wget/1.12 (LINUX-GNU)" "-"
58.19.57.99--[04/jun/2017:05:23:30 +0800] "Get/blog http/1.0" 301 233 "-" "wget/1.12 (LINUX-GNU)"-"

ImportTimepin=0 whileTrue:with Open ('Access.log','RB') as F:ip_list=[] F.seek (PIN) forLineinchF:ip=Line.decode (). Split () [0]Print(IP) ip_list.append (IP ) forIpinchSet (ip_list):ifIp_list.count (IP) >=200:                Print('blacklist:%s, number of visits:%d'%(Ip,ip_list.count (IP))) pin=F.tell ()Print(PIN) time.sleep (5)

Python3 from zero single row 2_ file read/write

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.