心得:
不知道为何突然释然了,看开了很多东西,没钱没车没房子,假如不努力你的生活会怎样,已经有很多人比你更强大了,你的时间很宝贵,不该去浪费了~
1.打开文件,获取文件内容:
with open("/home/tianjain/123.py","r") as f:
for line in f:
print(line.rstrip())
打开这个文件,读取后,并存给f,逐行打印
2.写入文件
with open("/home/tianjain/file.py","w") as f:
f.write("I love python")
参数w,可以写入文件,但会刷新文件所有内容
3 附加内容
with open("/home/tianjain/file.py","a") as f:
f.write("I love python")
参数a,可以写入文件,附加模式
4.当然读取文件还有自定义的函数
f.read() 读取整个文件
f.readline 读取一行
f.readlines 读取整个文件,将每一行当成一个元素存成列表
with open("/home/tianjain/file.py","r") as f:
a=f.readlines()
print(a[0].rstrip())
读取第一行内容,消除多余空行,如果内容有用到可以用这种方法,但我一般用遍历的方法多一些,执行较快,不占内存.
5.存储数据
存储的数据我们一般放在json文件内,用户的操作数据都可以去存储
import json
num=[1,2,3,4,5]
filename="/home/tianjain/file1.json"
with open(filename,"w") as f:
json.dump(num,f)
with open("/home/tianjain/file1.json","r") as f:
n=json.load(f)
print(n)
json.dump() 相当于写入文件
json.load() 相当于读取文件内容
import json
def greet():
try:
with open("/home/tianjain/file1.json","r") as d:
a=json.load(d)
print("your name is : %s"%a)
except FileNotFoundError:
username=input("please input your name")
with open("/home/tianjain/file1.json","w") as f:
json.dump(username,f)
print("we will rember your name")
else:
print("welcom back")
greet()
为了避免出现异常,我们使用try except结构,尝试运行try语句,如果出现FileNotFoundError,就执行except语句,如果没有出现异常则执行try和else语句内容
如果需要同时使用多个文件:
import os
def read():
with open(filename,"r") as f:
for line in f:
print(line)
file=os.listdir()
print(file)
for filename in file:
print(filename)
read()
遍历路径下所有的文件内容
拼接路径的操作
import os
>>> a="hello"
>>> os.path.join(a,"home")
'hello\\home'
在windows系统下拼接路径尽量用双\\反斜杠,用/拼接路径有时会出问题