目录
- 利用内置函数open获取文件对象
- 文件操作的模式之写入
- 文件对象的操作方法之写入保存
利用内置函数open获取文件对象
- 功能:
- 用法:
- 参数说明∶
- 返回值:
- 举例:
f = open('d://a.txt' , ‘w')
文件操作的模式之写入
文件对象的操作方法
In [1]: import os
In [2]: current_path = os.getcwd()
In [3]: current_path
Out[3]: 'D:\\My_Files\\Python Project\\pythonlean\\python_package'
In [4]: f = open(current_path + '/' + 'a.txt', 'w', encoding='utf-8')
In [5]: f.write('hello 小明')
Out[5]: 8
In [6]: f.close()
In [7]: path = os.path.join(current_path, 'a.txt')
In [8]: path
Out[8]: 'D:\\My_Files\\Python Project\\pythonlean\\python_package\\a.txt'
In [9]: f = open(path, 'w', encoding='utf=8')
In [10]: f.write('你好 小华')
Out[10]: 5
In [11]: f.close()
In [12]: f = open(path, 'w+', encoding='utf=8')
In [14]: f.write('你好 insane')
Out[14]: 9
In [15]: f.close()
In [16]: f = open(path, 'w', encoding='utf=8')
In [17]: f.write('hahaha')
Out[17]: 6
In [18]: f.read()
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-18-571e9fb02258> in <module>
----> 1 f.read()
UnsupportedOperation: not readable
In [19]: f.close()
In [20]: f = open(path, 'w+', encoding='utf=8')
In [21]: f.write("nono")
Out[21]: 4
In [22]: f.read() # 默认为读取最后一个字符
Out[22]: ''
In [23]: f.seek(0) # 指定从头开始读取
Out[23]: 0
In [24]: f.read()
Out[24]: 'nono'
In [28]: f = open(path, 'ab', encoding='utf-8')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-53d8520ae678> in <module>
----> 1 f = open(path, 'ab', encoding='utf-8')
ValueError: binary mode doesn't take an encoding argument
Unhandled exception in event loop:
File "D:\Program Files\Python38\lib\asyncio\proactor_events.py", line 768, in _loop_self_reading
f.result() # may raise
File "D:\Program Files\Python38\lib\asyncio\windows_events.py", line 808, in _poll
value = callback(transferred, key, ov)
File "D:\Program Files\Python38\lib\asyncio\windows_events.py", line 457, in finish_recv
raise ConnectionResetError(*exc.args)
Exception [WinError 995] 由于线程退出或应用程序请求,已中止 I/O 操作。
Press ENTER to continue...
In [29]: f = open(path, 'ab', encoding='utf-8')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-53d8520ae678> in <module>
----> 1 f = open(path, 'ab', encoding='utf-8')
ValueError: binary mode doesn't take an encoding argument
In [30]: f = open(path, 'ab')
In [31]: f.write('Python很有意思')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-06909b58890f> in <module>
----> 1 f.write('Python很有意思')
TypeError: a bytes-like object is required, not 'str'
In [32]: f.write(b'Python很有意思')
File "<ipython-input-32-b260791cc53c>", line 1
f.write(b'Python很有意思')
^
SyntaxError: bytes can only contain ASCII literal characters.
In [33]: message = 'python很有意思'
InIn [34]:
In [34]: _message = message.encode('utf-8')
In [35]: _message
Out[35]: b'python\xe5\xbe\x88\xe6\x9c\x89\xe6\x84\x8f\xe6\x80\x9d'
In [36]: f.write(_message)
Out[36]: 18
In [37]: f.close()
In [38]: f = open(path, 'a+')
In [39]: f.write('1\n')
Out[39]: 2
In [40]: f.write('2\n')
Out[40]: 2
In [42]: f.close()
In [44]: l = ['今天天气很好', '很适合学习python', 'python是非常简单的语言']
In [45]: f = open(path, 'a')
In [46]: f.writelines(l)
In [47]: f.close()
In [48]: f = open(path, 'a', encoding='utf-8')
In [49]: l = ['今天天气很好\n', '很适合学习python\n', 'python是非常简单的语言\n']
In [50]: f.writelines(l)
In [51]: f.close()
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/22 11:11
# @Author : InsaneLoafer
# @File : package_open.py
import os
def create_package(path):
if os.path.exists(path):
raise Exception('%s 已经存在不可创建' % path)
os.makedirs(path)
init_path = os.path.join(path, '__init__.py')
f = open(init_path, 'w', encoding='utf-8')
f.write('# coding:utf-8\n')
f.close()
class Open(object):
def __init__(self, path, mode='w', is_return=True):
self.path = path
self.mode = mode
self.is_return = is_return
def write(self, message):
f = open(self.path, mode=self.mode, encoding='utf-8')
try:
if self.is_return and message.endswith('\n'):
message = '%s\n' % message
f.write(message)
except Exception as e:
print(e)
finally:
f.close()
if __name__ == '__main__':
current_path = os.getcwd()
# path = os.path.join(current_path, 'test2')
# create_package(path)
open_path = os.path.join(current_path, 'b.txt')
o = Open(open_path)
o.write('你好 娃娃')