Python小记:6.文件的读取、写入

读取:

  • open用于开文件
  • as设置别名
  • with用于指定访问文件的范围,出了with作用域自动关闭文件 (此时想获取读取的数据,可以在with里用一个容器接受文件中的内容)
with open('pai.txt') as file_object:
    """
    读取文件内容,内部有中文字符就不行:
    'gbk' codec can't decode byte 0x82 in position 51: illegal multibyte sequence
    """
    content=file_object.read()
    print(content)

读取并去掉空格:

filename='pai.txt'
with open(filename) as file_object:
    """
    读取文件内容,内部有中文字符就不行:
    'gbk' codec can't decode byte 0x82 in position 51: illegal multibyte sequence
    """
    lines=file_object.readlines()

str_content=''
for line in lines:
    str_content += line.strip()

print(str_content.rstrip())
print(len(str_content))

写入:

“”"
调用open() 时提供了两个实参。
第一个实参也是要打开的文件的名称;
第二个实参(‘w’ )告诉Python,我们要以写入模式 写入模式 打开这个文件。

打开文件时,可指定读取模式(‘r’ )、写入模式 (‘w’ )、附加(‘a’ )或让你能够读取和写入文件的模式(‘r+’ )。

如果你省略了模式实参,Python将以默认的只读模式打开文件。
“”"

filename = 'pai.txt' 
with open(filename, 'w') as file_object: 
    file_object.write("I love programming.\n")
    #写入多行时,主要要加换行符
    file_object.write("I love programming.")
   #注意  Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str() 将其转换为字符串格式。 
"""
如果你要写入的文件不存在,函数open() 将自动创建它。

然而,以写入('w' )模式打开文件时千万要小心,因为如果指定的文件已经存在,

Python将在返回文件对象前清空该文件。
"""

不覆盖继续写入

"""
如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。

你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。

如果指定的文件不存在,Python将为你创建一个空文件。 
"""

with open(filename, 'a') as file_object: 
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

实际项目增加文件操作的健壮性:

加入异常处理机制:try-except-else
在无法打开时,提示错误:

filename = 'pai.txt'  
try:      
	with ope	n(filename) as f_obj:          
		contents = f_obj.read()  
except FileNotFoundError:      
	msg = "Sorry, the file " + filename + " does not exist."      
	print(msg)  
else:   
	print(content)

这样的提示大家可能回想,正常运行错误了就会报错,这个报错还有什么意义呢?

  • 首先编译器内部的报错可能会泄漏一些信息,不安全
  • 其次,内部报错,整个程序运行就终止了,如果我想读取多个文件,有一个文件打不开,后续的就都打不开了。

使用多个文件:

1.首先来一个函数包含我们需要的功能:

def print_file_content(filename):
	try:      
		with ope	n(filename) as f_obj:          
			contents = f_obj.read()  
	except FileNotFoundError:      
		msg = "Sorry, the file " + filename + " does not exist."      
		print(msg)  
	else:   
		print(content)

2.下面就可以统一操作多个文件了:

#这样的操作,即使siddhartha.txt打不开,也不影响后面两个文件的操作

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] 
for filename in filenames:    
	print_file_content(filename)

你可能感兴趣的:(Python小记)