Python Programming--File manipulation

Source: Internet
Author: User
Tags fread serialization

Classification

1. Text files

Stores regular strings, consisting of several lines of text, with each line ending with a newline character ' \ n '

2. binary files

Store objects in byte strings, common graphics images, executables, database files, Office documents, and more

1 #Create a file2>>FW = open ('Sample.txt','w+', encoding='Utf-8')3>>s ='text read \ n sample.txt w+\n'4>>Fw.write (s)5>>fw.close ()6 #View Sample.txt7 Text Read mode8Sample.txt w+9 Ten #suggested form, keyword with to manage resources automatically One>>s ='text read \ n sample.txt w+\n' A>>with Open ('Sample.txt','w+', encoding='Utf-8') as FW: ->>Fw.write (s) - #determine if the file object is closed the>>fw.colsed - True -  - #Add File Contents +>>s ='hello\n' ->>with Open ('Sample.txt','A +', encoding='Utf-8') as FA: +>>Fa.write (s) A Text Read mode atSample.txt w+ - Hello -  - #Read File contents - #read a row ->>fread = open ('Sample.txt','R', encoding='Utf-8') in>>Fread.readline () - 'text Read method \ n' to>>Fread.readline () + 'sample.txt w+\n' ->>Fread.readline () the 'hello\n' *  $ #read all rows at oncePanax Notoginseng>>fread = open ('Sample.txt','R', encoding='Utf-8') ->>Fread.readlines () the['text Read method \ n','sample.txt w+\n','hello\n'] +  A #read fixed number of characters the>>fread = open ('Sample.txt','R', encoding='Utf-8') +>>fread.read (4) - 'Text Read'
>>fread.close ()

You can use Dir () to view methods associated with an object, using Help () to view the usage of the method

1 >>fread = open ('sample.txt','r', encoding= ' Utf-8 ' )2 >>fread.colse ()3 >>dir (fread)4 # view read () function usage 5 >>help (fread.read)

Serialization of files

Serialization is the process of converting in-memory data into binary form without losing data types.

1. Using the Pickle module

Pickle is a common and fast binary file serialization module

1 #using pickle Dump to write binary files in sequence2 ImportPickle3f = open ('Sample_pickle.dat','WB')4 5Alist = [[2,3,4],[6,7,8]]6Aset = {'a','b','C'}7Atuple = ( -5,-3,-1)8Astr ='Beijing welcomes you, welcome!'9adic = {'name':'Jin','Sex': None}Ten Try: One pickle.dump (alist,f) A pickle.dump (aset,f) - pickle.dump (atuple,f) - pickle.dump (astr,f) the pickle.dump (adic,f) - except: -     Print('Write Error') - finally: + f.close () -  + #using pickle load to read binary files in turn AFR = Open ('Sample_pickle.dat','RB') at Try: -x=Pickle.load (FR) -     Print(x) -x=Pickle.load (FR) -     Print(x) -x=Pickle.load (FR) in     Print(x) -x=Pickle.load (FR) to     Print(x) +x=Pickle.load (FR) -     Print(x) the except: *     Print('Read Error') $ finally:Panax NotoginsengFr.close ()

2. Using a struct module

1 Importstruct2 ImportBinascii3  4Values = (1, b'Good', 1.22)#string must be a byte stream type5s = struct. Struct ('I4SF')6Packed_data = S.pack (*values)#Sequence Unpacking7Unpacked_data =S.unpack (packed_data)8   9 Print('Original values:', values)Ten Print('Format String:', S.format) One Print('Uses:', S.size,'bytes') A Print('Packed Value:', Binascii.hexlify (packed_data)) - Print('unpacked Type:', type (unpacked_data),'Value:', Unpacked_data) -  the Out : -Original values: (1, b'Good', 1.22) -Format string:b'I4SF' -Uses:12bytes +Packed value:b'01000000676f6f64f6289c3f' -Unpacked Type: <class 'tuple'> Value: (1, b'Good', 1.2200000286102295)

Python Programming--File manipulation

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.