In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the method of operating Python files". In the daily operation, I believe that many people have doubts about the methods of operating Python files. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what is the method of operating Python files?" Next, please follow the editor to study!
1. Correlation function of dictionary
Correlation function of dictionary
# Dictionary related function dic = {} # add # 1. Common method (recommended) dic ["top"] = "369" dic ["middle"] = "left hand" dic ["bottom"] = "Jack Love" print (dic) # 2.fromkeys uses a set of keys and default values to create the dictionary tup = ("a", "b", "c") # fromkeys (container for keys, default) dic = {} .fromkeys (tup) None) print (dic) # Note (the three keys in the dictionary point to the same list by default) dic= {} .fromkeys (tup, []) print (dic) dic ["a"] .append (1) print (dic) # retrofit dic= {} dic ["top"] = [] dic ["middle"] = [] dic ["bottom"] = [] dic ["top"] .append ("the boy") print (dic) # Delete dic= {'top':' 369' 'middle':' left-handed, 'bottom':' Jack love'} # pop () delete the key-value pair (if there is no such key, you can set a default value to prevent error reporting) res = dic.pop ("middle") print (res) print (dic) # you can set a second parameter value for pop to prevent the key from having a res = dic.pop ("middle1234") "the key does not exist") print (res) # popitem () Deletes the last key pair dic = {'top':' 369pairs, 'middle':' left hand', 'bottom':' Jack Love'} res = dic.popitem () print (res) print (dic) # clear () empty dictionary dic.clear () print (dic) # change # update () batch update (update if there is this key) Add without this key) # recommended # add dic_new = {"jungle": "karsa", "support": "sapphire"} dic = {'top':' 369, 'middle':' left hand', 'bottom':' Jack Love'} dic.update (dic_new) print (dic) # update dic_new = {"top": "the bug", "support": "xboyww" if you have the key "xiaozhang": "Wang Sicong"} dic.update (dic_new) print (dic) # (understand) dic.update (ww= "Wang Wen", zl= "Zhang Lei") print (dic) # check # get () get the value by key (if you do not have this key, you can set the default value to prevent error reporting) dic = {"top": "the bug", "support": "xboyww", "xiaozhang": "Wang Sicong"} # res = dic ["top123"] # get when getting the dictionary key If it does not exist, no error will occur. What is returned is Noneres = dic.get ("top123") # you can prompt the default value when the key is not available. Res = dic.get ("top123", "sorry, the key does not exist") print (res) # other operations # keys () forms dictionary keys into a new iterable object dic = {"top": "the bug", "support": "xboyww" "xiaozhang": "Wang Sicong"} res = dic.keys () print (res, type (res)) # values () forms a new iterable object * res = dic.values () print (res, type (res)) # items () assembles the key-value pairs of the dictionary into tuples to form a new iterable object * * res = dic.items () print (res) Type (res)) # for i in res: # print (I) for KMagi v in res: print (KMagnev) 2. Operation _ function of the set
Related operations of the set (intersection and complement)
# 1. Related operations of the collection (intersection and compensation) # intersection () intersection set1 = {"easy closing Qianxi", "Wang Yibo", "Liu PDD", "Wang Wen"} set2 = {"Ni Ping", "Zhao Zhongxiang", "Beetle Big windmill", "Little Dragon Man" "Wang Wen"} res = set1.intersection (set2) print (res) # Abbreviations & res = set1 & set2print (res) # difference () difference res = set1.difference (set2) print (res) # Abbreviations-res = set1-set2print (res) # union () Union res = set1.union (set2) print (res) # Abbreviations | res = set1 | set2print (res) # symmetric_difference () symmetric difference (covered by complementary sets) ) res = set1.symmetric_difference (set2) print (res) # abbreviation ^ res = set1 ^ set2print (res) # issubset () determine whether it is a subset set1 = {"Andy Lau" "Aaron Kwok", "Jacky Cheung", "Wang Wen"} set2 = {"Wang Wen"} res = set2.issubset (set1) print (res) # abbreviated res = set2
< set1print(res)#issuperset 判断是否是父集set1 = {"刘德华","郭富城","张学友","王文"}set2 = {"王文"}res = set1.issuperset(set2)print(res)# 简写res = set1 >Set2print (res) # isdisjoint () detects whether two sets do not intersect, True intersect Falseset1 = {"Andy Lau", "Aaron Kwok", "Jacky Cheung", "Wang Wen"} set2 = {"Wang Wen"} res = set1.isdisjoint (set2) print (res) # 2. Collection related function # add # add () add data to the collection # add set1 = {"Wang Wen"} set1.add ("Wang Wei") print (set1) # update () iteratively add # add a bunch of set1 = {"Wang Wen"} lst = ["a", "b", "c"] lst = "ppp" # iteration, unordered Will automatically remove set1.update (lst) print (set1) # delete setvar = {'Liu PDD',' Little Dragon Man','Ni Ping' 'Zhao Zhongxiang'# clear () empties the collection # setvar.clear () # print (setvar) # pop () randomly deletes a data in the collection # res = setvar.pop () # print (res) # print (setvar) # discard () deletes the specified value in the collection (recommended for non-existent deletion) * * setvar.discard ("Liu PDD111111") # success# setvar.discard ("Liu PDD") ) # print (setvar) # remove () Delete the specified value in the collection (error is reported if it does not exist) (understand) # setvar.remove ("Liu PDD111") # error# setvar.remove ("Liu PDD") # print (setvar) # 3. Frozen set (extra understanding) "" frozenset simply can only do intersection and compensation operations, not add or delete operations "" lst = ["Wang Wen", "Song Jian", "he Xutong"] fz1 = frozenset (lst) print (fz1) Type (fz1)) # cannot add or remove elements from frozen collections # fz1.add (1) # fz1.update ("abc") # fz1.discard ("Wang Wen") # Frozen collections can only do intersection and complement lst2 = ["Wang Wen", "Wang Tongpei", "Liu Yigai"] fz2 = frozenset (lst2) print (fz2, type (fz2)) # intersection res = fz1 & fz2print (res) # iterate through frozen sets for i in fz2: print (I) 3. File basic operation # File operation "" syntax: fp = open (file, mode, code set) fp = > file io object (file handle) I = > input input o = > outpur output fp.read () read file content fp.write () write file content "" # 1. File write operation # (1) Open file fp = open ("ceshi1.txt", mode= "w", encoding= "utf-8") # Open refrigerator door # (2) write content fp.write ("hold the elephant in") # hold the elephant in # (3) close the file fp.close () # close the refrigerator door # 2. File read operation # (1) Open file fp = open ("ceshi1.txt", mode= "r", encoding= "utf-8") # (2) read content res = fp.read () # (3) close file fp.close () print (res) # 3. File storage binary byte stream: `A data format used to transfer or store data. A byte stream that begins with "abc" b requires that the data can only be characters in ascii encoding. Cannot be Chinese # converting string and byte stream (Bytes stream) types (parameters are written into converted character encoding format) # encode () encoding converting string to byte stream (Bytes stream) # decode () decoding converting Bytes stream to string "" data = b "abc" data = "Chinese" .encode ("utf-8") print (data) Type (data)) res = data.decode ("utf-8") print (res,type (res)) # utf-8 the next Chinese language occupies 3 bytes data = "Chinese" .encode ("utf-8") # calculates the total byte size print (len (data)) # restores the middle character byte stream to the original character "res = b"\ xe4\ xb8\ xad ".decode () print (res) # 4. File storage binary byte stream "" if you are storing a binary byte stream, specify the mode wb, do not specify the encoding code set, otherwise report an error "" fp = open ("ceshi2.txt", mode= "wb") strvar = "red carp, green carp and donkey" .encode ("utf-8") fp.write (strvar) fp.close () # 5. File read binary byte stream fp = open ("ceshi2.txt", mode= "rb") res = fp.read () fp.close () print (res) print (res.decode ()) # 6. Copy file "" all pictures, audio and video need to be stored and transferred through a binary byte stream. "# first read out the binary byte stream of the original file # relative path to find the collection .png relative to the current 3.py file # fp = open (" collection .png " Mode= "rb") # absolute path to find the collection. PNG look up from the lowest level to find fp = open (r "D:\ python32_python\ day01\ collection .png", mode= "rb") res = fp.read () fp.close () # calculate the number of bytes in the file = > file size print (len (res)) # when writing a binary byte stream to another file, it is equivalent to copying fp = open ("set 2.png") Mode= "wb") fp.write (res) fp.close () 4. File expansion mode
Extended mode of file operation
# read () function: read the number of characters (the parameters in it represent the number of characters) Note: read # seek () from the current cursor to the right Function: adjust the position of the pointer (the parameters inside represent the number of bytes) seek (0) move the cursor to the beginning of the file seek (0) move the cursor to the end of the file # tell () function: all bytes on the left side of the current cursor (return bytes) "# 1.r+ read before writing "" fp = open ("ceshi3.txt" Mode= "r +", encoding= "utf-8") # read res = fp.read () # move the cursor to the beginning print (fp.read ()) fp.close () through seek before writing fp.write ("ab") # read fp.seek (0) # "# 2.r+ write first and read later"fp = open (" ceshi3.txt ", mode=" r + ", encoding=" utf-8 ") # move the cursor to the end, otherwise in r mode The original character will be overwritten fp.seek (0Power2) # write fp.write ("cd") # move the cursor to the beginning of the file fp.seek (0) # read res = fp.read () print (res) fp.close () "# 3.w+ readable and writable, clear rewrite (new file can be created by default)" fp = open ("ceshi4.txt", mode= "w+" Encoding= "utf-8") fp.write ("abc") fp.seek (0) print (fp.read ()) fp.close () "" # 4.a+ readable and writable, append write (new file can be created by default) "" fp = open ("ceshi5.txt", mode= "a +" Encoding= "utf-8") fp.write ("def") # read content fp.seek (0) print (fp.read ()) fp.close () "" # 5.r+ and a+ write overwrite mode based on the current cursor location A + mode forces the cursor to be placed at the end of the file to append "# fp = open (" ceshi5.txt ", mode=" r + ", encoding=" utf-8 ") fp = open (" ceshi5.txt ") Mode= "a +", encoding= "utf-8") fp.seek (3) # from the position of the first three bytes # fp.write ("zxc") # mode forces the cursor to be placed at the end of the file to append to print (fp.read ()) fp.close () "# 6. The use between fp = open (" ceshi5.txt ", mode=" r + ") Encoding= "utf-8") fp.seek (4) # tell the number of bytes of all content on the left side of the current cursor res = fp.tell () print (res) # in r + mode read (2) represents reading 2 characters in rb mode read (2) represents reading 2 bytes fp.read (2) # all character content print (fp.tell ()) fp.close () # 7. Note (when seek moves, it may move to the middle of a Chinese character byte, resulting in the original byte cannot be parsed) "" fp = open ("ceshi6.txt", mode= "r +", encoding= "utf-8") fp.seek (3) print (fp.read ()) fp.close () # print ("you" .encode ()) # b'\ xe4\ xbd\ xa0' "# 8.with syntax automatically implements file closure operation # method 1. Read binary byte stream "" with open ("set 2.png", mode= "rb") as fp: res = fp.read () with open ("set 3.png", mode= "wb") as fp: fp.write (res) "" # method II. Continue to simplify with open ("set 3.png", mode= "rb") as fp1, open ("set 4.png", mode= "wb") as fp2: res = fp1.read () fp2.write (res) Tip: string, list, tuple use + to make a concatenated set unordered to remove duplicates if this data does not want others to modify arbitrarily, give these collections to Frozen open a class To create an object decode (), which is not written in parentheses. The default is utf-8w mode. If the file already exists, it is also emptied first and then written to the content a mode. Data can only be appended, not read data a + can read data, read data is not affected, seek can be used (will force the cursor to the end of the file to append write It is also useless to move the cursor with seek) seek should still be cautious when moving bytes, because a Chinese character accounts for 3 bytes, and one character should take up one byte. If a Chinese character is not intercepted completely, it will report an error seek (0) seek (0mem2) and pure English and pure Chinese files using seek. In fact, instead of using seek to move our content, we use files such as read readline. The latter functions to achieve the operation of closing the file must be written here, on the "what is the method of Python file operation" learning is over, I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.