Python基础-txt⽂件读写-txt_read_write.py Python基础-txt/json⽂件读写-txt_read_write.py
尾部包含了json⽂件的读写
# ~ coding=GBK
import json
#绝对路径
file_path = r'E:\python_work\python basics\txtReadWrite\'
# ~ file_path = 'E:\\python_work\\python basics\\txtReadWrite\\'
# ~ 读取整个⽂件
with open(file_path)as file_object:
# ~ with open('folder\') as file_object:#相对路径
# ~ with open('D:\python_work\python basics\txtReadWrite\') as file_object:
# ~ 关键字with可使⽂件不再需要访问时将其关闭,交给python⾃动处理
# ~ 在当前执⾏的⽂件所在⽬录中查指定的⽂件'',
# ~ 返回⽂件对象存储于file_object
contents = ad()
print(contents.rstrip())#rstrip()⽅法删除字符串末尾的空⽩
# ~ 逐⾏读取
with open('')as file_object:
for line in file_object:#注意获取的line字符串的末尾有⼀个换⾏符
print(line.rstrip())
# ~ 创建⼀个包含⽂件各⾏内容的列表
with open('')as file_object:
lines = adlines()
print(lines)
for line in lines:
print(line.rstrip())
# ~ 使⽤⽂件的内容
pi_str =''
for line in lines:
pi_str += line.strip()
print(pi_str)
print(len(pi_str))
filename ='pi_'
with open(filename)as file_object:
lines = adlines()
for line in lines[0:3]:
print(line.rstrip())
print(lines[:3])
print("This txt has "+str(len(lines))+" lines.")
pi_str =''
for line in lines:
pi_str += line.strip()
print(pi_str[:52]+'...')
print(len(pi_str))
# ~ 检测⽣⽇数据是否包含在圆周率⼀百万位中
hint ="Enter your birthday, in the form yymmdd: (enter 'q' to quit) "
while True:
birthday =input(hint)
if birthday =='q':
break
elif birthday in pi_str:
elif birthday in pi_str:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appears in the first million digits of pi!")
# ~ 写⼊⽂件
filename =''
with open(filename,'w')as file_object:
#写⼊⽂件名不存在时⾃动创建
#'w'表⽰以写⼊模式打开这个⽂件,当⽂件存在时将先清空原有内容,再写内容,千万注意!#'r'表⽰只读模式(默认),'a'表⽰附加模式
#'wb'表⽰写⼆进制⽂件,'rb'表⽰读⼆进制⽂件(图⽚)
file_object.write("I love programing.\n")
file_object.write("I love programing2.\n")
# ~ 存储json格式数据
numbers =[2,3,5,7,9,11]
filename ='nums.json'
with open(filename,'w')as f:
python怎么读取py文件json.dump(numbers,f)
with open(filename,'r')as f1:
nums = json.load(f1)
print(nums)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论