打开文件
# 文件路径可以是绝对路径也可以是相对路径
f = open('data.txt') # 打开文件,默认以只读模式 ("r") 打开
# 打开文件,默认以写入模式 ("w") 打开
f = open('data.txt', "w")
# 指定编码类型
f = open('scores.txt', encoding='gbk')
f.close() # 关闭文件,释放资源
读文件
f = open('data.txt') # 打开文件,默认以只读模式 ("r") 打开
data = f.read() # 读取文件
print (data) # 输出读取到的文件内容
f.close() # 关闭文件,释放资源
# 其他 API
readline() #读取一行内容
readlines() #把内容按行读取至一个list中
写文件
data = 'I will be in a file.\nSo cool!'
out = open('output.txt', 'w') # 打开文件,以写入模式 ("w") 打开
out.write(data)
out.close()
上一篇:1.字符串
下一篇:3.requests模块使用指南