打开文件
mode:
r: 只能读文件
w: 只能写入(清空文件内容)
a+: 读写(文件追加写入内容)
f = open('doc/hello.txt',mode='a+')
文件读写操作
f.write('java\n') #追加写入java 换行
关闭文件
f.close()
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()) # 读取文件内容
因为指针已经移动到末尾,所以后面没有内容可以读取到
import os
import platform
print(os.name)
try:
uname = os.uname()
except Exception:
uname = platform.uname()
finally:
print(uname)
envs = os.environ
# os.environ.get('PASSWORD')
print(envs)
BASE_DIR = os.path.dirname(__file__)
setting_file = os.path.join(BASE_DIR, 'dev.conf')
print(setting_file)
将python对象编码成json字符串
users = {
'name':'westos', "age":18, 'city':'西安'}
json_str = json.dumps(users)
with open('doc/hello.json', 'w') as f:
# ensure_ascii=False:中文可以成功存储
# indent=4: 缩进为4个空格
json.dump(users, f, ensure_ascii=False, indent=4)
print("存储成功")
print(json_str, type(json_str))
将json字符串解码成python对象
with open('doc/hello.json') as f:
python_obj = json.load(f)
print(python_obj, type(python_obj))
如何安装pandas?
pip install pandas -i https://pypi.douban.com/simple
如何安装对excel操作的模块?
pip install openpyxl -i https://pypi.douban.com/simple
import pandas
hosts = [
{
'host':'1.1.1.1', 'hostname':'test1', 'idc':'ali'},
{
'host':'1.1.1.2', 'hostname':'test2', 'idc':'ali'},
{
'host':'1.1.1.3', 'hostname':'test3', 'idc':'huawei'},
{
'host':'1.1.1.4', 'hostname':'test4', 'idc':'ali'}
]
df = pandas.DataFrame(hosts)
df.to_excel('doc/hosts.xlsx')
print('success')
# 1. 加载文件中所有的单词
with open('doc/song.txt') as f:
words = f.read().split()
# 2. 统计
from collections import Counter
counter = Counter(words)
result = counter.most_common(5)
print(result)
方法二
with open('doc/song.txt') as f:
words = f.read().split()
result = {
}
for word in words:
if word in result:
# result[word] = result[word] + 1
result[word] += 1
else:
result[word] = 1
#小拓展: 友好打印信息
import pprint
pprint.pprint(result)