import os os.getcwd() #取得当前的执行路径 os.chdir('C:/Users/ourgame/Desktop/headFirstPython') #进入某个路径 data = open('sketch.txt') #打开文件 print(data.readline(),end='') #读取一行,文件指针会向下移动 print(data.readline(),end='') #此句与上句输出不一样 data.seek(0) #data指针返回到文件起始位置 for each in data: print(each,end='') #输出整个文件 data.close() #关闭文件
for each_line in data: (role,line_spoken) = each_line.split(':') print(role,end='') print(' said: ',end='') print(line_spoken,end='')
try: data = open('sketch.txt') for each_line in data: # if each_line.find(":") > -1: try: (role,line_spoken) = each_line.split(':',1) print(role,end='') print(' said: ',end='') print(line_spoken,end='') except ValueError: pass except IOError as err: #使用as将异常对象,并将其赋值给一个标识符 print('File Error:'+str(err)) #‘+’用于字符串直接的连接 finally: if 'data' in locals(): data.close()
try: with open('its.txt','w') as data: print("it's...",file=data) #输出默认为sys.stdout except IOError as err: print("File Error:"+str(err)) #str()将对象转换为字符串
with open("a.txt",'w') as a_out,open("b.txt",'w') as b_out:
out = opne("data.txt","w") print("test data",file=out) out.close()
使用
if 'data' in locals(): xxxxxx
print("abc",file=myout)
import pickle ...... with open('mydata.pickle','wb') as mysavedata: #要以二进制操作 pickle.dump(['a','b'],mysavedata) ...... with open('mydata.pickle','rb') as my_restore_data: #以二进制取 a_list = pickle.load(my_restore_data) print(a_list) #一旦数据回到程序中,就可以像任何其他数据对象一样操作了
except pickle.PickleError as per: print("Pickel Error:"+str(per))