python-file operation management


1. Basic operation of files

g)
insert image description here

1. Open the file

"""
mode:
r: can only read files
w: can only write (clear file content)
a+: read and write (file append content)
"""
f = open('doc/hello.txt',mode='a+')

2. File read and write operations

f.write(‘java\n’)

3. Close the file

f.close()
insert image description here

Two, with statement

with语句:
with open('doc/test.txt', 'w+') as f:
    f.write('hello world\n') # 写入文件
    f.seek(0, 0)      # 移动指针到文件最开始!!!
    print("当前指针的位置:", f.tell())
    f.seek(0, 2)      # 移动指针到文件末尾
    print("当前指针的位置:", f.tell())
    print(f.read())   # 读取文件内容

insert image description here

3. OS module

import  os
import platform
# 1. 获取操作系统类型
print(os.name)
# 2. 获取主机信息,windows系统使用platform模块, 如果是Linux系统使用os模块
"""
try: 可能出现报错的代码
excpt: 如果出现异常,执行的内容
finally:是否有异常,都会执行的内容
"""
try:
    uname = os.uname()
except Exception:
    uname = platform.uname()
finally:
    print(uname)

# 3.获取系统的环境变量
envs = os.environ
# os.environ.get('PASSWORD')
print(envs)

# 4. 目录名和文件名拼接
# os.path.dirname获取某个文件对应的目录名
# __file__当前文件
# join拼接, 将目录名和文件名拼接起来。
BASE_DIR = os.path.dirname(__file__)
setting_file = os.path.join(BASE_DIR, 'dev.conf')
print(setting_file)

insert image description here
insert image description here

4. JSON module

insert image description here

5. Store as an Excel file

insert image description here

Six, word frequency statistics exercises

insert image description here
insert image description here


Guess you like

Origin blog.csdn.net/Gong_yz/article/details/131070373