Python read and write files

Python read and write file

1.Python read and write file

fr=open("readfile.txt","r")  
fw=open("writefile.txt","w")

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

print fr.readlines()  
fw.write("===write line===")  
fw.close()

fr.seek(0,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()

fr.close()

#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

#coding=utf-8

import struct

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

value1=100  
value2=200

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

fb.write(str1)

fb.seek(0,0)

str2=fb.readline()

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.