Python file operations

Source: Internet
Author: User

First, the basic process of file operation

The computer system is divided into three parts: the hardware, the operating system and the application.

Applications that we write in Python or other languages need to be saved on the hard drive if we want to keep the data permanently, which involves the application operating hardware, and it is well known that the application is not able to manipulate the hardware directly. The operating system encapsulates complex hardware operations into a simple interface for use by the user/application, where the file is the operating system provided to the application to manipulate the virtual concept of the hard disk, and the user or application can save its own data permanently by manipulating the file.

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

# 1. Open the file, get the file handle and assign a value to a variable f=open ('a.txt','r', encoding='utf-8'# The default open mode is R#2. Manipulating files with a handle data=f.read ()#3. Close file f.close ()

Errors that may occur:

1.UnicodeDecodeError: File is not stored and opened in the same way

2: You need to add r before the path or escape with \ \ If the path contains \t,\n

Two, file encoding

F=open (...) is opened by the operating system file, then if we do not specify the encoding for open, then the default encoding of the opening file is obviously the operating system, the operating system will use its own default encoding to open the file, under Windows is GBK, under Linux is Utf-8

# this uses the knowledge of character encoding: to ensure that it is not garbled, how the file is stored in what way, it will be opened in what way. F=open ('a.txt','r', encoding='utf-8  ')
Three, open mode of the file

File handle = open (' File path ', ' mode ')

Read

E:\\new.txt Absolute Path
Relative path: A file in the same folder is a relative path

R, read-only mode "default mode, file must exist, not present, throw exception"

RB, generally used in non-text type files: pictures, Videos

File download and upload function in b mode

r+, reading and writing (read first, write later) r+b

f = open ('e:\ new text document '. txt','r+'utf-8 ') )print(F.read ()) f.write ('asdadd') f.close () 

Five Modes of reading:

1, F.read () read it all

 f = open ( " log   ", Mode="  r   ", Encoding="   Utf-8   " ) content  = F.read (3) #   R mode: n is read by character   Print   
f = open ('log', mode='rb'#  RB mode: N is read by byte print(content) F.close ()#  bytes---> strs = b' \xe4\xb8\xb0\xe5\x8e '. Decode ('utf-8')print(s)

2, F.readline () read by line

f = open ('log', encoding='utf-8'= f.readline ()  print= f.readline ()print(line1) f.close ()

3, F.readlines () each row is placed in the list as an element

f = open ('log', encoding='utf-8'= f.readlines ()  Print(lines) f.close ()

4. Recommended way: Cyclic reading

f = open ('log', encoding='utf-8') for in F:    print(i) f.close ()

5, F.read (n)

R mode read by number of characters

RB mode read by number of bytes

f = open ('e:\ new text document '. txt','r'gbk' = F.read (3)print(content) F.close () 

Add: Bytes-->str A Chinese character 3 bytes, 4, 5 will be an error

s = B ' \xe4\xb8\xb0.decode (' Utf-8 ') print (s) #丰

Write

F.write (' Laozhang ') if there is no file, then create a file to write content, if there is a file to delete the original file, and then write.

f = open ('Log','W', encoding='Utf-8') F.write (' Laozhangit's SB .') F.close () F= Open ('Log1','W', encoding='Utf-8') F.write (' LaozhangIt's still SB .') F.close ()

WB mode requires a string to be written. Encode converted to binary and added encoding

Write read w+ first read, F.seek (0) cursor moves to the beginning

f = open ('log1','wb') f.write ('  Laozhang is still sb'. Encode ('utf-8')) F.close ()

Additional

Only a AB is added

f = open ('e:\ new text document '. txt','a''gbk'  ) f.write ('3') f.close ()

The breakpoint continues to use the tell and seek, all in accordance with the byte to adjust the position of the cursor.

. Truncate intercept, according to bytes to intercept.

With open (' Log ', ' r ', encoding = ' utf-8 ') as F1:

Print (F1.read ())

Method Summary:

defClose (self, *args, **kwargs):#Real Signature UnknownClose FilePass    defFileno (self, *args, **kwargs):#Real Signature UnknownFile DescriptorPass    defFlush (self, *args, **kwargs):#Real Signature Unknownflush File Internal buffersPass    defIsatty (self, *args, **kwargs):#Real Signature Unknowndetermine if the file is a consent TTY devicePass    defRead (self, *args, **kwargs):#Real Signature Unknownreads the specified byte dataPass    defReadable (self, *args, **kwargs):#Real Signature Unknownwhether it is readablePass    defReadLine (self, *args, **kwargs):#Real Signature UnknownRead only one row of dataPass    defSeek (self, *args, **kwargs):#Real Signature Unknownspecify pointer position in filePass    defSeekable (self, *args, **kwargs):#Real Signature Unknownwhether the pointer can be manipulatedPass    defTell (self, *args, **kwargs):#Real Signature UnknownGet pointer positionPass    defTruncate (self, *args, **kwargs):#Real Signature Unknowntruncate data, preserving only the previous data specifiedPass    defWritable (self, *args, **kwargs):#Real Signature Unknownwhether it can be writtenPass    defWrite (self, *args, **kwargs):#Real Signature UnknownWrite ContentPass

Common methods:

Read readable ReadLine readlines for loop

Seek tell write writeable

Change file:

#1, create a new file.#2. Read the original file.ImportOswith Open ('Log', encoding='Utf-8') as F1, open ('Log.bak','W', encoding='Utf-8') as F2:#3. Change the contents of the original file in the way you want, and write the new file.Old_content =f1.read () new_content= Old_content.replace ('Alex','SB') F2.write (new_content)#4, delete the original file.Os.remove ('Log')#5. Rename the new file to the original filename.Os.rename ('Log.bak','Log')

Python file operations

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.