1 # open() 方法的介绍 2 open(...) 3 open(name[, mode[, buffering]]) -> file object 4 5 Open a file using the file() type, returns a file object. This is the 6 preferred way to open a file. See file.__doc__ for further information. 7 # 查看file.__doc__ 8 >>> print(file.__doc__) 9 file(name[, mode[, buffering]]) -> file object 10 11 Open a file. The mode can be 'r', 'w' or 'a' for reading (default), 12 writing or appending. The file will be created if it doesn't exist 13 when opened for writing or appending; it will be truncated when 14 opened for writing. Add a 'b' to the mode for binary files. 15 Add a '+' to the mode to allow simultaneous reading and writing. 16 If the buffering argument is given, 0 means unbuffered, 1 means line 17 buffered, and larger numbers specify the buffer size. The preferred way 18 to open a file is with the builtin open() function. 19 Add a 'U' to mode to open the file for input with universal newline 20 support. Any line ending in the input file will be seen as a '\n' 21 in Python. Also, a file so opened gains the attribute 'newlines'; 22 the value for this attribute is one of None (no newline read yet), 23 '\r', '\n', '\r\n' or a tuple containing all the newline types seen. 24 25 'U' cannot be combined with 'w' or '+' mode. 26 # 文件打开模式对比关系 27 28 r ,只读模式【默认】 29 w,只写模式【不可读;不存在则创建;存在则清空内容;】 30 x, 只写模式【不可读;不存在则创建,存在则报错】 31 a, 追加模式【可读; 不存在则创建;存在则只追加内容;】 32 # 字节的方式打开 33 1. 只读 rb 34 2. 只写 wb 35 3. 追加 ab 36 # 测试用例 37 #!/usr/bin/env python 38 # -*- coding:utf-8 -*- 39 40 if __name__ == '__main__': 41 'functions is test open ' 42 file1 = open('first.py','r+',encoding='utf-8') 43 print("打印该文件内容") 44 print(file1.read()) 45 file1.write("This is a test open file function") 46 print(file1.read()) 47 file1.close() 48 if file1.closed : 49 print("这个文件已经关闭。") 50 else: 51 file1.close() 52 # 在Python 3.X 版本以上,open 方法 53 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 54 Open file and return a stream. 55 56 如果是以字节的形式访问 57 #!/usr/bin/env python 58 # -*- coding:utf-8 -*- 59 60 if __name__ == '__main__': 61 'functions is test open ' 62 file1 = open("two.py","wb") 63 file1.write(bytes("BONC,让数据改变工作和生活",encoding="gbk")) 64 file1.close() 65 file2 = open("two.py",'r') 66 print(file2.read()) 67 file2.close() 68 69 ## 普通模式打开,Python 内部提供机制将 二进制代码转换为 字符字符串 70 # 计算机的存储单元是 0 1 71 # 文件指针 file.seek, file.tell 72 # 读文件可以在指针位置读写,写文件一般是在末尾追加,指针移动到末尾。 73 # w+ 先清空,在写的之后,就可以读了。 74 # mode a (追加)打开文件的时候已经将文件指针移动到文件尾部。
我除了胖点,再没啥优点。
浙公网安备 33010602011771号