# 第十节、从文件读取数据#1、读取文件中所有数据 read()with open('D:/stream/hello.java') as f:c = f.read()print(c)'''Hello World .Hello World .9'''filename = 'D:/stream/hello.java'with open(filename) as f:c = f.read()print(c.strip())#删除首尾空白#2、逐行读取filename = 'D:/stream/world.java'with open(filename) as f:for line in f:print(line)'''I am luckly!I am luckly!I am luckly!I am luckly!I am luckly!I am luckly!'''# 3、创建一个包含文件各行内容的列表filename = 'D:/stream/hello.txt'with open(filename, encoding = 'utf-8') as f: #指定读取文件的格式lines = f.readlines()for line in lines:print(line.strip())'''阿萨大大啊飒飒额外的是qweq'''# 4、使用文件的内容filename = 'D:/stream/hello.txt'with open(filename, encoding = 'utf-8') as f: #指定读取文件的格式lines = f.readlines()strs = ''for line in lines:strs += line.strip()print(strs)print(len(strs))'''阿萨大大啊飒飒额外的是qweq15'''# 二、写入文件#1、写入内容filename = 'D:/stream/world.txt'with open(filename, 'w') as f:f.write('I like speaking .')# 2、向一个文件写入多行filename = 'D:/stream/world.txt'with open(filename, 'w') as f:f.write('I like speaking .\n')f.write('I like speaking .\n')# 3、附加内容到文件filename = 'D:/stream/world.txt'with open(filename, 'a') as f:f.write('I like myself .\n')f.write('I like myself .\n')# 三、异常#1、处理异常try:print(5/0)except ZeroDivisionError:print('Erro')#2、else代码块try:m = 5/1except ZeroDivisionError:print('Erro')else:print(m)# 3、使用多个文件def count_words(filename):with open(filename, encoding='utf-8') as f:coent = f.read()word = coent.split()print(filename,'中单词个数:',len(word))ls = ['D:/stream/hello.txt','D:/stream/world.txt']for filename in ls:count_words(filename)'''D:/stream/hello.txt 中单词个数: 3D:/stream/world.txt 中单词个数: 16'''# 四、存储数据# 1、存储数import jsonm = [1,2,3,4]filename = 'D:/stream/number.json'with open(filename, 'w') as f:json.dump(m, f)# 1、读取数import jsonfilename = 'D:/stream/number.json'with open(filename) as f:numbers = json.load(f)print(numbers)'''[1, 2, 3, 4]''
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。