一:文件保存
def save_to_file(file_name, contents): fh = open(file_name, ‘w‘) fh.write(contents) fh.close() save_to_file(‘mobiles.txt‘, ‘your contents str‘)
结果:
将字符串修改则覆盖原来的字符串
将字符串用变量替代
将 fh = open(file_name, ‘w‘)写的权限去掉报错:
fh.write(contents)
io.UnsupportedOperation: not writable
写权限不加引号报错:
fh = open(file_name, w)
NameError: name ‘w‘ is not defined
def save_to_file(file_name):中少一个参数报错:
save_to_file(‘mobiles.txt‘,data)
TypeError: save_to_file() takes 1 positional argument but 2 were given
def save_to_file(file_name,contents):
fh = open(file_name, ‘w‘)
fh.write(contents)
fh.close()
print(type(fh),fh)
data=‘machangwei‘
save_to_file(‘mobiles.txt‘,data)
打印结果:
<class ‘_io.TextIOWrapper‘> <_io.TextIOWrapper name=‘mobiles.txt‘ mode=‘w‘ encoding=‘cp936‘>
当data=123或列表、元组、字典等时报错,必须是字符串:
TypeError: write() argument must be str, not int
当其他类型想要输出到文件时需要变成字符串: