Ab1f = open ('Test.log','r+', encoding='Utf-8')2F.write ('Sdhgrbfds in SAF')3 Print(F.tell ())#View the current pointer position, in characters4F.seek (4)#Specifies the current pointer position, in bytes5 Print(F.read (4))6F.truncate ()#read the data before the pointer7 Print(F.tell ())8F.close ()View CodeSecond: Common file operations
f = open (' Data ', ' R ') #以只读形式打开 (default is read-only)
f = open (' F.txt ', encoding= ' latin-1 ') #python3.0 Unicode file
string = F.read () #把文件读入一个字符串中
String = F.read (N) #读取指针后的N个字节
string = F.readline () #读取下一行, including end-of-line identifiers
Alist = F.readlines () #读取整个文件到字符串列表
F.write () #将字符串写入文件
F.writelines () #将列表内所有字符串写入文件
F.close () #手动关闭
F.flush () #把输出缓冲区刷到硬盘中
F.seek (N) #将文件指针移到N处, in bytes
For line in open (' Data '):
Print (line) #文件迭代器将文件一行行读出
Open (' F.txt ', ' R '). Read () #read all @ ance into string
Three: Storing and parsing Python objects in a file
X, y, z = 41,42,43
s = ' spam '
D = {' A ': 1, ' B ': 2} #字典对象
L = [' A ', ' B ', ' C '] #列表
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 ()) #将文件内容输出
#从文件中取出数据, and judge 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))
‘‘‘
# Extract data from file and convert to pre-storage type
fi = open (' F.txt ')
A = Fi.readline (). Rstrip () #rstrip () Remove line break
Print (A,type (a))
b = Fi.readline (). Rstrip (). Split (', ') #字符串的split () method, writes a delimiter in parentheses, and divides the string into a list.
Print (B,type (b))
c = Fi.readline ()
c = eval (c) #调用内置函数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))