代码一
#! /usr/bin/env python
"""
@Time : 2018/8/24 22:29
@Author : Damao
@Site : Life is short. I use python.
@File : test1.py
@Software : PyCharm
"""
"""没有指定文件或文件不存在会报错"""
def test():
f = open('abc.txt','r',encoding='utf-8')
print(f.read())
f.close()
if __name__ == '__main__':
test()
代码二
#! /usr/bin/env python
'''
__Time__ : 2018/8/24 22:36
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test2.py
__Software__ : PyCharm
'''
"""处理异常"""
def main():
f = None
try:
f = open('致橡树.txt', 'r', encoding='utf-8')
print(f.read())
except FileNotFoundError:
print('无法打开指定的文件!')
except LookupError:
print('指定了未知的编码!')
except UnicodeDecodeError:
print('读取文件时解码错误!')
finally:
if f:
f.close()
if __name__ == '__main__':
main()
代码三
#! /usr/bin/env python
'''
__Time__ : 2018/8/24 22:41
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test3.py
__Software__ : PyCharm
'''
"""with语句"""
def main():
try:
with open('致橡树.txt','r',encoding='utf-8') as f:
print(f.read())
except FileNotFoundError:
print('无法打开指定的文件!')
except LookupError:
print('指定了未知的编码!')
except UnicodeDecodeError:
print('读取文件时解码错误!')
if __name__ == '__main__':
main()
代码四
#! /usr/bin/env python
'''
__Time__ : 2018/8/24 22:44
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test4.py
__Software__ : PyCharm
'''
"""多种方式读取文件"""
def test():
# 一次性读取所有文件内容
with open('致橡树.txt','r',encoding='utf-8') as f:
print(f.read())
# for循环读取
with open('致橡树.txt',mode='r',encoding='utf-8') as f:
for i in f:
print(i,end='')
# 按行读取文件到列表中
with open('致橡树.txt', mode='r', encoding='utf-8') as f:
l = []
for i in f:
l.append(i[:-2])
# if i[-2:] == '\n':
# # i = i[:-2]
# l.append(i[:-2])
for index in range(len(l)-1):
if l[index] == '':
del l[index]
print(l)
# lines = f.readlines()
# print(lines)
if __name__ == '__main__':
test()
代码五
#! /usr/bin/env python
'''
__Time__ : 2018/8/24 22:57
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test5.py
__Software__ : PyCharm
'''
a = '1213213213'
print(a[:-2])
print(a[-2:])
代码六
#! /usr/bin/env python
'''
__Time__ : 2018/8/24 23:12
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test6.py
__Software__ : PyCharm
'''
from math import sqrt
def is_prime(n):
"""判断素数的函数"""
assert n > 0
for factor in range(2, int(sqrt(n)) + 1):
if n % factor == 0:
return False
return True if n != 1 else False
def main():
filenames = ('C:\\MYTEST\\a.txt', 'C:\\MYTEST\\b.txt', 'C:\\MYTEST\\c.txt')
fs_list = []
try:
for filename in filenames:
fs_list.append(open(file=filename, mode='w', encoding='utf-8'))
for number in range(1, 10000):
if is_prime(number):
if number < 100:
fs_list[0].write(str(number) + '\n')
elif number < 1000:
fs_list[1].write(str(number) + '\n')
else:
fs_list[2].write(str(number) + '\n')
except IOError as ex:
print(ex)
print('写文件时发生错误!')
finally:
for fs in fs_list:
fs.close()
print('操作完成!')
if __name__ == '__main__':
main()
代码七
#! /usr/bin/env python
'''
__Time__ : 2018/8/25 21:34
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test7.py
__Software__ : PyCharm
'''
"""读写二进制文件,下面代码实现复制文件的功能"""
def test():
try:
with open(file='mm.jpg',mode='rb') as f:
data = f.read()
with open(file='C:\\MYTEST\\copy_mm.jpg',mode='wb') as f1:
f1.write(data)
except FileNotFoundError as e:
print("文件未找到",e)
except IOError as e:
print("读写文件时错误",e)
print("程序执行完毕。")
if __name__ == '__main__':
test()
代码八
#! /usr/bin/env python
'''
__Time__ : 2018/8/25 21:50
__Author__ : Damao
__Site__ : Life is short. I use python.
__File__ : test8.py
__Software__ : PyCharm
'''
"""
保存json格式文件
dump - 将Python对象按照JSON格式序列化到文件中
dumps - 将Python对象处理成JSON格式的字符串
load - 将文件中的JSON数据反序列化成对象
loads - 将字符串的内容反序列化成Python对象
"""
import json
def test_save_json_data():
json_data ={
'name': 'damao',
'age': 1,
'qq': 123456,
'friends': ['小红', '小明'],
'cars': [
{'brand': 'BYD', 'max_speed': 180},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 320}
]
}
try:
with open(file='C:\\MYTEST\\test_json_data.json',mode='w',encoding='utf-8') as f:
json.dump(json_data,f)
except IOError as e:
print("读写错误",e)
print("json数据保存成功!")
def test_read_json_filedata():
try:
with open(file="C:\\MYTEST\\test_json_data.json",mode='r',encoding='utf-8') as f:
a = json.load(f)
print(json.dumps(a,ensure_ascii=False,indent=4,separators=(':',','))) # 格式化json数据输出
except IOError as e:
print("读写错误", e)
print("json数据读取成功!")
if __name__ == '__main__':
# test_save_json_data()
test_read_json_filedata()