Python文件读写

注意事项:

1. python在写文件之后必须正确关闭文件,否则会输入更多的乱码。

2. python在读写文件之间切换时必须重新打开文件(这点和其他语言一样c++)

 1 fo = open("abc.txt", "a+")
 2 #print "Name of the file: ", fo.name
 3 #fo.close()
 4 #print "Closed or not : ", fo.closed
 5 #print "Opening mode : ", fo.mode
 6 #print "Softspace flag: ", fo.softspace
 7 str = fo.read()
 8 position  = fo.tell()
 9 print "position :", position
10 fo.seek(0, 0)
11 fo.write("hello world ")
12 fo.close() #正常关闭,未关闭会有乱码写入
13 fo = open("abc.txt", "a+") #读写文件操作之间切换时要重新打开文件
14 str = fo.read() 
15 print str
View Code
原文地址:https://www.cnblogs.com/zhonghuasong/p/4873827.html