文件
读文件
使用with语句的时候,文件会自动关闭
1.最简单的打开文件:(没法读取中文,文件中有中文则报错)
with open('路径') as file: contes = file.read() print(contens.rstrip()) #删除多余空白,因为文件自带一个换行,print自动输出一个换行
read(10)里面也可以设置int型数据,用来设置读取几个字符。 tell()是返回当前句柄所在位置。 seek(3)将句柄设置到3位置
还可以这样,但是需要手动关闭文件(file.close) file = open('路径') print(file)
2.逐行读取:
filename = '路径'
with open(filename) as file: for line in file: print(line)
#其他方法 with open(filename) as file: lines = file.readlines() 返回文件内容的列表
#lines是一个列表,这样的话这个文件内的元素就可以在with代码块以外使用了。
for line in lines: print(line)
3.读取出来的文件的类型还是字符串。
4.abc.replace(‘qwe’,‘asd’),可以吧abc字符串内的全部qwe替换为asd
#写文件
1.filename = '路径' #文件不存在的话,自动创建新的
with open(filename,'w') as file: file.write("I Love You")
2.同样写入党也只能是字符串,想存其他类型的话,需要先转换成字符串。
3.write()不会自动加入换行符,需要的话手动添加。
异常 1.ZeroDivisionError 除数等于0的时候报错。
print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.")
while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") try: answer = int(first_number) / int(second_number) except ZeroDivisionError: #有错误的话运行except内的代码,没的话跳过 print("You can't divide by 0!") else: #try运行成功后,运行else内的代码。 print(answer)
2.FileNotFoundError 文件不存在的时候报错。
filename = 'alice.txt'
try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError : msg = "Sorry, the file " + filename + " does not exist." print(msg) #pass 失败时一声不吭 else: # Count the approximate number of words in the file. words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")
3.title = 'Alice in wonderland' title.split() #以空格为分隔符,将字符串拆成多个部分。
#运行结果为:['Alice' , 'in' , 'wonderland']
数据存取 1.将数据存下来,待到下次运行时,可以保存这个结果,比如说游戏存档。
2.需要用到json库。
json.dump() , 存,接收两个实参,数据和文件对象 json.load() , 取
import json #存 numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json' with open(filename, 'w') as file_object: json.dump(numbers, file_object)
#取
with open(filename) as file_object: numbers = json.load(file_object)
print(numbers)