文件读写和函数

文件读写

# f= open('a.txt','r+',encoding='utf-8')
# res = f.read()
# print(res)

# f.write('123')
# f.read()

# f.write('哈哈')
# f.read()

# res = f.read()
# print(res)
# f.write('abc')
# res = f.read()
# print(res)
# f.close()



#r  read    只能读不能写,文件不存在的时候会报错
#w  write   文件不存在的话,自动创建,不能读 会清空原来的文件内容
#a  追加      追加模式不会清空原来的内容,但是不能读 文件不存在会自动创建

#r+ 读写模式    文件不存在的时候会报错     可以写,但是写到第一行(打开文件位置在文件最开始    )
#w+ 写读模式    文件不存在的话,自动创建,会清空原来的文件内容  可以读,但是读不到内容
#a+ 追加读模式   文件不存在的话,自动创建,可写可读,读不到内容(打开文件位置在文件最后)

#有r没有文件报错
#有w文件内容清空

#文件指针



# f= open('a.txt','a+',encoding='utf-8')
# res = f.read()
# print(res)

# f = open('a.txt',encoding='utf-8')
#res = f.read()     #读取文件里面所有的内容
# print(f.readline())     #读取一行内容
# print(f.readline())
# print(f.readlines())
# f.seek(0)
# print(f.read())

# f= open('a.txt','a+',encoding='utf-8')
# f.seek(0)
# # print(f.tell())     #当前文件指针的位置
# # print(f.readline())
# #print(f.tell())
# f.truncate()        #从文件指针位置删除内容
# # res = f.read()
# # # # print(res)
#
# f.write('abc')


# l = ['123\n','12345\n','789\n']
# f.writelines(l)

# with open('a.txt') as f,open('b.txt','w') as f2:
#     res = f.read()
#     print(res)

# with open('a.txt','r',encoding='utf-8') as f:
#     for line in f:
#         print('每次循环的内容是',line)

函数

# def meteor():
#     print('这是一个函数')
#     pass        #没想好的话先写个pass
#
# meteor()

#实现某个功能的一些代码
# def calc(a,b):      #a、b是函数的形参
#     print(a,b)
#     return a+b
#
# resault = calc(1,2)       #实参,实际参数
#函数里遇到return,函数立即结束
# #返回值
# print(resault)

#写一个函数来校验是不是合法的小数
#1.24
#
#-0.123
#1.判断是否只有一个小数点
#2.小数点左边是一个整数,小数点右边也是一个整数
#3.左边以负号开头,且只有一个负号,负号后面是整数,小数点右边也是一个整数

#num = input('请输入价格:')

def check_float(num):
    num = str(num)
    if num.count('.')==1:
        left,right = num.split('.')
        if left.isdigit() and right.isdigit():
            return True
        elif not left.startswith('-') and left[1:].isdigit() and right.isdigit():
            return True
    return False

print(check_float(1.4))
print(check_float(-1.4))
print(check_float(1))
print(check_float('s.1'))
print(check_float(--1.4))
print(check_float('--1.4'))
print(check_float('1.4.00'))
print(check_float('1.'))
print(check_float('.'))

import json

def write_file(d,file):
    with open(file,'w',encoding='utf-8') as fw:
        json.dump(fw,d,indent=4,ensure_ascii=False)

def read_file(file):
    with open(file,'r',encoding='utf-8') as fr:
        return json.load(fr)

结果

True
False
False
False
True
False
False
False
False

转载于:https://www.cnblogs.com/meteor9/p/10731910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值