一、文件和异常
1.1从文件中读取数据
读取整个文件
读取文件先要创建一个文件,在程序的同一目录下。
greet.txt
“Hello World!
Hello World!
Hello World!
Hello World!”
with open('greet.txt') as file_object: contents=file_object.read() print(contents)
如果txt文件中有中文,输出出现乱码时,可以with open(‘greet.txt’,encoding=‘UTF-8′) as file_object:。
1.2open()
要以任何方式使用文件时,都必须先打开文件,才能访问。函数open()接受一个参数,打开文件的名称。在这里open(‘greet.txt’)返回的是一个表示文件greet.txt的对象,然后将该对象赋给file_object供以后使用。
1.3关键字with
关键字with在不再需要访问文件后将其关闭。也可以调用open()和close()来打开文件。但是不推荐。
1.4read()
方法read()读取文件的全部内容,并将其作为一个长长的字符串赋给变量contents。
二、逐行读取
with open('greet.txt',encoding='UTF-8') as file_object: for line in file_object: print(line)
三、创建一个包含文件各行内容的列表
with open('greet.txt',encoding='UTF-8') as file_object: lines=file_object.readlines() for line in lines: print(line.rstrip())
3.1readlines()
readlines()从文件读取每一行,并将其存在一个列表中。
四、查找字符串中是否含有特定的字符串
greet_str='' with open('greet.txt',encoding='UTF-8') as file_object: lines=file_object.readlines() for line in lines: greet_str+=line input_str=input('输入你想查找的字符串') if input_str in greet_str: print('有') else : print('无')
4.1对字符串进行修改
message='Hello World!' print(message.replace('World','China'))
五、写入文件
5.1写入空文件
with open('greet.txt','w',encoding='UTF-8') as file_object: file_object.write('我爱编程')
本文来源gao!daima.com搞$代!码网
w’告诉Python要以写入模式打开这个文件。打开文件时可以指定模式:读取模式’r‘,写入模式’w’,附加模式‘a’或读写模式’r+‘。如果省略了模式实参,则默认只读模式打开文件。