赞
踩
以二进制模式打开文件,写入字符串内容一定要编码操作
- """
- 1. 打开文件
- 路径:t1.txt(w模式:文件存在清空再写,文件不存在创建再写)
- 模式:wb(w,写 write;b,二进制 binary)
- """
- file_object = open('t1.txt', mode='wb')
-
- # 2. 写入内容
- file_object.write("51自学".encode("utf-8"))
-
- # 3. 关闭文件
- file_object.close()
'运行
- """
- 1. 打开文件
- 路径:t1.txt
- 模式:wt(w,写 write;t,文件 text)
- """
- file_object = open('t1.txt', mode='wt', encoding='utf-8') # 写文件必须要加mode,如果不加encoding则写入内容是乱码
-
- # 2. 写入内容
- file_object.write("51自学")
-
- # 3. 关闭文件
- file_object.close()
'运行
- # 实现:将用户注册内容写入到文本文件中
- username = input("请输入用户名:")
- password = input("请输入密码:")
- data = "{}-{}".format(username, password)
- file_object = open('files/info.txt', mode='wt', encoding='utf-8')
- file_object.write(data)
- file_object.close()
- # 如果使用w写入文件,会先清空文件,再向文件中写入内容
- # 解决办法:使用w写入文件不要反复打开文件
- file_object = open('files/info.txt', mode='wt', encoding='utf-8')
- while True:
- username = input("请输入用户名:")
- if username.upper() == "Q": # upper()函数将字符转为大写
- break
- password = input("请输入密码:")
- data = "{}-{}\n".format(username, password)
-
- file_object.write(data)
- """
- 放循环里面会报ValueError: I/O operation on closed file.
- 原因是:打开只操作一次,文件关闭放循环内部,文件关闭以后没执行打开就不能写入内容
- """
- file_object.close()

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。