1.读取TXT文本
f = open("./file_name.txt", "r")
lines = f.readlines()
for line in lines:
print(line)
2.鲁棒性很强的round函数
def new_round(_float, _len):
# 参数_float:浮点数;_len:四舍五入后保留小数点后_len位
# 输出:保留小数点后_len位的四舍五入的数字
if isinstance(_float, float):
if str(_float)[::-1].find('.') <= _len:
return(_float)
if str(_float)[-1] == '5':
return(round(float(str(_float)[:-1]+'6'), _len))
else:
return(round(_float, _len))
else:
return(round(_float, _len))
感谢热苏斯是有潜力超越姆巴佩的在这篇四舍五入就用round( )?Python四舍五入的正确打开方式!中下面的评论
3.创建CSV文件
# 导入csv库
import csv
# 创建csv文件
path = "file.csv"
with open(path, 'w', newline="") as f:
csv_write = csv.writer(f)
csv_head = ["A", "B", "C", "D", "E", "F"]
csv_write.writerow(csv_head)
# 行写入数据
with open(path, 'a+', newline="") as f:
csv_write = csv.writer(f)
data_row = ['a', 'b', 'c', 'd', 'e', 'f']
csv_write.writerow(data_row)
结果:
A,B,C,D,E,F——[Head]
a,b,c,d,e,f——[Data]
4.鲁棒性较强的删除文件
if os.path.exists(file_path):
os.remove(file_path)
if os.path.exists(file_path) == False:
print("OK!")
else:
print("Someting Error!")
else:
print("File NOT Exist")
5.对连续的值进行真值判断
# 如果当a,b,c,d都为真时,执行其他的操作
if a and b and c and d:
print("OK!")
else:
print("Try!")