Python read and write files

Python read and write file

1.Python read and write file


print fr.readline()  
print fr.tell()

print fr.readlines()  
fw.write("===write line===")  
fw.close(),0) #The first parameter represents the number of bytes, after which a parameter represents the relative position, 0- start, 1- current, 2- end 
for line in fr :  
    print line  
    print fr.tell()


#File mode
#a :to append mode to open, can only write

#r+,w+,a+ :Read and write mode, the difference is as follows:  
#r+ :From the beginning to cover write 
#w+ :Clear file after write 
#a+ :Append from end

#Text mode plus b is binary mode,Need to use the sturct module pack and unpack

2.Python write binary file


import struct

fb=open("binary.txt","wb+") #First clear file, binary read and write mode


str1=struct.pack("ii",value1,value2) #Convert any type of data into a specific format string



print struct.unpack("ii",str2) #Convert strings to data in any format

#Format     C Type              Python   
x           pad byte            no value    
c           char                string of length 1  
b           signed char         integer  
B           unsigned char       integer    
h           short               integer  
H           unsigned short      integer  
i           int                 integer  
I           unsigned int        long  
l           long                integer  
L           unsigned long       long  
q           long long           long  
Q           unsigned long long  long  
f           float               float  
d           double              float  
s           char[]              string  
p           char[]              string  
P           void *              integer

Pingbacks are closed.

Comments are closed.