python_ file processing


One, character encoding

  1. The memory is fixed using unicode encoding
  2. The data is first generated in the memory in the unicode format, if you want to transfer it needs to be converted to bytes format

# unicode -------> enconde( u t f - 8 ) -------> bytes

Get the bytes, you can store it in a file or transfer it over the network

# bytes --------> enconde( u t f - 8 ) -------> unicode

  1. Strings are recognized as unicode in Python 3

String encode in Python 3 gets bytes

Strings in Python 2 are bytes

Python 2 add'u' before the string, which is unicode

  1. File processing

Process: Open the file ===> get the file handle and assign it to the variable ====> manipulate the file through the handle ==> close the file

Read the file:

1 f =open( ‘aaaa.py ’ , ‘ r ’ ,encoding = ‘utf-8’ )23print( f.readline(),end= ‘’)#Read a line
 45 print( f.readlines(), end=’’ )#Read all, no line break
 67 print( f.readable())#Readable file
 89 print( f.writable())#Unwritable file
1011 f.close()#It must be closed after the end, otherwise it will occupy memory

Write file:

f =open( ‘new_2’, ‘w’,encoding=’utf-8’ )print( f.readable())#Unreadable

print( f.writable())#Writable

f.write( ‘888888\n’ )#Append single line

f.write( ‘999999\n’ )#Append

f.writelines([ ‘787878\n’ , ‘878787\n’])#Append multiple lines

f.close()#Close file

Append:

f=open('new_2','a',encoding='utf-8')print(f.readable())        #Unreadable

print(f.writable())         #Writable

f.write('888888\n')       #Append single line

f.write('999999\n')

f.writelines(['787878\n','878787\n'])       #Append multiple lines

f.close()

# rb

f=open('aaaa.py','rb')    #Open in bytes

print(f.read().decode('utf-8'))

Copy picture:

f=open('1.jpg','rb')      #Open 1 in rb way.JPG

data=f.read()           #data gets the content of f

print(data)

f2=open('3.jpg','wb')      #Open as write

f2.write(data)         #Write the content of data to f2

f2.close()

f.close()

# ab, append in binary form

f=open('new_3.txt','ab')

f.write('aaaaa\n'.encode('utf-8'))
withopen('aaaa.py','r',encoding='utf-8')as read_f,\

  open('aaaa_new.py','w',encoding='utf-8')as write_f:

 data=read_f.read()

 write_f.write(data)

Take each line of the file in a loop:

withopen('a.txt','r',encoding='utf-8')as f:while True:

  line=f.readline()if not line:breakprint(line,end='')

 
 lines=f.readlines() #Only for small files

 print(lines)
 

 data=f.read()print(type(data))for line in f: #Recommended Use

  print(line,end='')

File modification:

Method 1: Only applicable to small files

1 import os
 23 withopen('a.txt','r',encoding='utf-8')as read_f,\
 45 open('a.txt.swap','w',encoding='utf-8')as write_f:67     data=read_f.read()89     write_f.write(data.replace('alex_SB','alex_BSB'))10111213 os.remove('a.txt')1415 os.rename('a.txt.swap','a.txt')

**# Method 2: **

import os

withopen('a.txt','r',encoding='utf-8')as read_f,\

  open('a.txt.swap','w',encoding='utf-8')as write_f:for line in read_f:

  write_f.write(line.replace('alex_BSB','BB_alex_SB'))

 

os.remove('a.txt')

os.rename('a.txt.swap','a.txt')

File function operation introduction

Function Description
file.read ([size] ) Read all contents of file
file.readline ([size] ) Read line by line
file.readlines ([size] ) Every line read as an element in list
file.write (str ) Write string to file
file.writelines (sequence or stringe) Write multiple lines to a file, the parameter can be an iterable object/list/tuple...
file.close() Close the opened file
file.fileno (self ) file descriptor
file.flush (self ) Flush the contents of the buffer to the hard disk
file.isatty (self ) Judge whether the file is a tty device, if it is a tty device, return True
file.readable (self ) Judge whether it is readable, return True if it is readable, otherwise return False
file.readline (self, limit=-1 ) Read only one line of data at a time
file.readlines (self, hint=-1 ) Take each line of content as an element of a list
file.tell(self) Get pointer position
file.seek(self,offset, whence=io.SEEK_SET) Specify the position of the pointer in the file
file.seekable(self) Is the pointer operable
file.writable(self) Whether it is writable
file.writlines(self,lines) The sequence of strings written to the file, the sequence can be any iterated object string
file.read(self,n=None) Read the specified byte data, and read all by default without adding parameters
file.write(self,s) write content to file

Recommended Posts

python_ file processing
Python file operation
"Python hands-on learning" Python processing .mat file
Python processing json summary
Python datetime processing time summary
Python on image processing PIL
Python implements TCP file transfer
Python tornado upload file function
Quick start Python file operation
Python file read and write operations
How to write python configuration file
Python file operation basic process analysis
Python PIL library image graying processing
Python processing PDF and CDF examples
Python implements ftp file transfer function
How Python operates on file directories
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python exec
Python realizes batch modification of file names
Python notes
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
Python file and directory operation code summary
python queue Queue
Python basics 4
Python basics 5
How to switch the hosts file using python
Python memory mapped file read and write method
How to deal with python file reading failure