Python basics __with open() usage

1. The difference between open and with open

After open() is completed, the close() method must be called to close the file, because the file object will occupy the resources of the operating system, and the number of files that the operating system can open at the same time is also limited. Since IOError may occur when reading and writing files, once If an error occurs, the subsequent f.close() will not be called. with open() can avoid this situation.

2. Code

#文件的读操作
with open('input_filename.txt','r') as f:#r为标识符,表示只读
   df=pd.read_csv(f)  
   print(f.read())
'''
其他标识符:
r:	以只读方式打开文件。
rb: 以二进制格式打开一个文件用于只读。
r+: 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+:以二进制格式打开一个文件用于读写。
'''
#文件的写操作
with open('output_filename.csv', 'w') as f:
   f.write('hello world')  
'''
其他标识符:
w:	打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb:	以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+:	打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+:以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a:打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab:	以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+:	打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+:以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
''' 4

3. Methods and properties

f.read([size])   #将文件数据作为字符串返回,可选参数size控制读取的字节数
f.readlines([size])   #返回文件中行内容的列表,size参数可选
f.write(str)   #将字符串写入文件
f.writelines(strings)   #将字符串序列写入文件
f.close()   #关闭文件

f.closed	#返回布尔值,文件已经被关闭为True,否则为False
f.mode	#Access文件打开时使用的访问模式
f.encoding	#文件所使用的编码
f.name	#文件名
f.newlines	#未读取到行分隔符时为None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束的列表
f.softspace	#为0表示在输出一数据后,要加上一个空格符,1表示不加。这个属性一般程序员用不着,由程序内部使用

4. Pay attention

  1. To read non-UTF-8 encoded text files, you need to pass the encoding parameter to the open() function.
  2. Calling read() when reading will read the entire content of the file at once. If the file is 10G, the memory will burst. To be on the safe side, you can call the read(size) method repeatedly, and read up to size bytes of content each time.
  3. Call readline() to read one line at a time, call readlines() to read all the contents at once and return the list line by line.
  4. Call as needed: If the file is very small, it is most convenient to read it once with read(); if the file size cannot be determined, it is safer to call read(size) repeatedly; if it is a configuration file, it is most convenient to call readlines()

Literature reference python reading files with open()

Guess you like

Origin blog.csdn.net/weixin_64974855/article/details/132614064