Ab1 f = open ('test. log', 'r + ', encoding = 'utf-8') 2 f. write ('sdhgrbfds in saf ') 3 print (f. tell () # view the current pointer position, in the unit of characters 4 f. seek (4) # specify the current pointer position, in bytes 5 print (f. read (4) 6 f. truncate () # Read the data before the pointer 7 print (f. tell () 8 f. close ()View CodeIi. Common File Operations
F = open ('data', 'R') # open in read-only mode (read-only by default)
F = open('f.txt ', encoding = 'Latin-1') # python3.0 Unicode file
String = f. read () # read the file into a string
String = f. read (N) # N Bytes after reading the pointer
String = f. readline () # Read the next row, including the end identifier of the row
Alist = f. readlines () # Read the entire file to the string list
F. write () # write a string to a file
F. writelines () # Write all strings in the list to a file
F. close () # manually close
F. flush () # fl the output buffer to the hard disk.
F. seek (N) # Move the file pointer to N, in bytes
for line in open('data'):
Print (line) # The file iterator reads a row of the file
open('f.txt','r').read() #read all at ance into string
3. Store and parse python objects in files
X, y, z = 41,42, 43
S = 'spam'
D = {'A': 1, 'B': 2} # dictionary object
L = ['A', 'B', 'C'] # list
F = open('f.txt ', 'w ')
F. write (s + '\ n ')
F. write ('% s, % s, % s \ n' % (x, y, z ))
F. write (str (D ))
F. write ('\ n ')
F. write (str (L ))
F. close ()
Print(open('f.txt '). read () # output the File Content
# Retrieve data from the file and determine its type
'''
A = fi. readline ()
B = fi. readline ()
C = fi. readline ()
D = fi. readline ()
Print (a, B, c, d, type (a), type (B), type (c), type (d ))
'''
# Retrieve data from the file and convert it to the type before storage
Fi = open('f.txt ')
A = fi. readline (). rstrip () # rstrip () Remove the line break
Print (a, type ())
B = fi. readline (). rstrip (). split (',') # The split () method of the string. Write a separator in the brackets to split the string into a list.
Print (B, type (B ))
C = fi. readline ()
C = eval (c) # Call the built-in function eval () to convert the string into executable python code.
Print (C, type (C), type (c ))
D = fi. readline ()
D = eval (d)
Print (D, type (D), type (d ))