一.文件基本操作

  1.文件的打开 

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作  

   文件句柄 = open('文件路径', '模式')

2.文件的读取

>>> f = open("f:/test.txt", "r")
>>> f.read()
'hello,world'
>>> f.close

  3.打开文件的模式有:  

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】
>>> f = open("f:/test.txt", 'r+')
>>> f.read()
'heheo,world~~'
>>> f.write("\naaaaaaa")
8
>>> f.tell()
22
>>> f.read()
''
>>> f.tell()
22
>>> f.seek(0)
0
>>> f.read()
'heheo,world~~\naaaaaaa'

"b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b
#以二进制文件写
f = open("file.txt", "wb")
str_data = "呵呵"
bytes_data = bytes(str_data, encoding='utf-8')
f.write(bytes_data)
f.close()
#以二进制文件读
f = open("file.txt",'rb')
data = f.read()
f.close()
print(data)
str_data = str(data,encoding="utf-8")
print(str_data)

注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

  4. r+, w+, x+, a+ 区别

  r+ 可读,可写,若文件不存在会报错,根据指针位置可写随意位置

  w+ 可写,可读,若文件不存在会创建,在进行写操作会清空文件内容

  x+ 可写,可读,若文件存在会报错,不存在则创建

  a+ 可写,可读,只能追加在文件尾部

5.文件内部支持操作:

readline()   逐行读取数据

#逐行去读,较省内存
f = open('log','r')
result = list()
for line in open('log'):
line = f.readline()
print(line)
result.append(line)
print(result)
f.close()

trancate(),从文件的首行首字符开始截断,截断文件为n个字符;无n表示从当前位置起截断;截断之后n后面的所有字符被删除

>>> with open("f:/test.txt" , 'r+') as f:
... f.seek(2)
... f.truncate(3)
...
2
3
>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
...
'hel'

read(),读取文件内容

>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
...
'hel'

write(),写入内容

>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
... f.write('llo' + '\n' + 'test')
... f.seek(0)
... f.read()
...
'hel'
8
0
'helllo\ntest'

readlines(), 将文件内容以列表的形式存放,---->[“第一行”, "第二行"] 

>>> with open("f:/test.txt" , 'r+') as f:
... temp = f.readlines()
... print(temp)
...
['heheo,world~~\n', 'aaaaaaa']

open(),打开文件

>>> f = open('f:/test.txt', 'r')

close(),关闭文件

 f.close()

flush(),强行刷入硬盘  

tell()  获取指针位置
seek()  跳转到某个位置

二.管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文

with open("log", 'r+') as f:
data = f.read()
print(data)

三.练习 

编写脚本实现 ,用户登录,注册,改密,删除功能

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#删除用户,修改密码
def login(username, password):
"""
用户登录验证
:param username: 用户名
:param password: 密码
:return: True成功,False失败
"""
f = open('log', 'r', encoding='utf-8')
for line in f:
line = line.strip()
userlist = line.split('$')
if username == userlist[0] and password == userlist[1]:
return True
return False def user_ex(username):
"""
用于检测用户是否存在
:param username: 用户名
:return: True 表示存在,False用户不存在
"""
with open('log','r',encoding='utf-8') as f:
for line in f:
line = line.strip()
userlist = line.split('$')
if username in userlist:
return True
return False def res(username, password):
"""
用于用户注册
:param username: 用户名
:param password: 密码
:return: True注册成功
"""
with open('log','a',encoding='utf-8') as f:
temp = "\n" + username + "$" + password
f.write(temp)
return True def change_pwd(username, password):
"""
用户修改密码
:param username: 用户名
:param password: 修改后的密码
:return: True修改成功,False修改失败
"""
file_object = open('log')
try:
lines=open('log','r').readlines()
for i in range(len(lines)):
if username in lines[i]:
test=lines[i].split('$')[1]
lines[i]=lines[i].replace(test,password)
open('log','w').writelines(lines)
return True
return False
finally:
file_object.close( ) def del_user(username):
"""
删除用户
:param username: 要删除用户名
:return: true 删除成功,False用户名不在列表中
"""
file_object = open('log')
try:
lines = open('log', 'r').readlines()
for i in range(len(lines)):
if username in lines[i]:
del lines[i]
print(lines)
open('log','w').writelines(lines)
return True
else:
return False
finally:
file_object.close() # def del_user(username):
# with open('log', 'r') as f:
# for line in f:
# if re.match("lisi", line):
# pass
# else:
# data = line
# with open('log', 'w+') as f:
# f.write(data)
# return True
# return False def main():
inp = input("1:登录;2:注册;3:删除用户;4:修改密码")
user = input("请输入用户名:")
pwd = input("请输入密码:")
if inp == "":
ret = login(user, pwd)
if ret:
print("登录成功")
else:
print("登录失败")
elif inp == "":
is_ex = user_ex(user)
if is_ex:
print("用户已存在,无法注册")
else:
resgister = res(user, pwd)
if resgister:
print("用户已成功注册")
else:
print("注册失败")
elif inp == "":
del_us = del_user(user)
if del_us:
print("已删除")
else:
print("无此用户")
elif inp == "":
is_chage = change_pwd(user, pwd)
if is_chage:
print("修改成功")
else:
print("无此用户") main()

2.haproxy配置文件更改操作

需求:

  1.匹配值 ,并将匹配到的内容以列表形式返回给用户

  2.插入内容,用户input数据后,将数据更新至配置文件中

global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 local2 info
defaults
log global
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
option dontlognull listen stats :8888
stats enable
stats uri /admin
stats auth admin:1234 frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 backend buy.oldboy.org
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000

配置文件

#!/usr/bin/env python
# -*- coding:utf-8 -*- def fetch(backend):
result = []
with open('ha.conf', 'r') as f:
flag = False
for line in f:
if line.strip().startswith('backend') and line.strip() == "backend " + backend:
flag = True
continue
if flag and line.strip().startswith('backend'):
break
if flag and line.strip():
result.append(line.strip()) return result def add(backend, record):
result = fetch(backend)
if not result:
# 无backend,无record
pass
else:
# 有backend
if record in result:
# 记录record
pass
else:
result.append(record)
with open('ha.conf', 'r') as old, open('new.conf', 'w') as new:
continue_flag = False
for line in old: if line.strip().startswith('backend') and line.strip() == "backend " + backend:
continue_flag = True
new.write(line)
for temp in result:
new.write(" "*8 + temp + "\n")
continue if continue_flag and line.strip().startswith('backend'):
continue_flag = False if continue_flag:
pass
else:
new.write(line) def add2(backend, record):
with open('ha.conf', 'r') as old, open('new.conf', 'w') as new:
in_backend = False
has_backend = False
has_record = False
for line in old:
if line.strip().startswith('backend') and line.strip() == "backend " + backend:
has_backend = True
in_backend = True
new.write(line)
continue if in_backend and line.strip().startswith('backend'):
if not has_record:
new.write(" "*8 + record + '\n')
new.write(line)
in_backend = False
continue if in_backend and line.strip() == record:
has_record = True
new.write(line)
continue if line.strip():
new.write(line) if not has_backend:
# 写backend,写record
new.write('backend '+ backend + '\n')
new.write(' '*8 + record + '\n') # ret = fetch("www.oldboy.org")
# print(ret) # add('www.oldboy.org', "server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000")
# add2('www.oldboy.org', "server 100.1.7.11 100.1.7.11 weight 20 maxconn 3000")

3. 号码段截取

需求:

  将文件中的第二列前三字节和后四字节以逗号分开,文件格式如下:

1,"1300000","山东","济南","中国联通","0531","250000"
2,"1300001","江苏","常州","中国联通","0519","213000"
3,"1300002","安徽","巢湖","中国联通","0565","238000"
4,"1300003","四川","宜宾","中国联通","0831","644000"
5,"1300004","四川","自贡","中国联通","0813","643000"

  需求目标:

1,"130","0000","山东","济南","中国联通","0531","250000"

代码实现:
def phone():
with open("mobile", "w+") as nf, open("Mobile.txt", "r") as f:
for row in f:
row = row.strip().split(',')
row = (row[:1] + [row[1][:4]+'"', '"' + row[1][4:]] + row[2:])
nf.write(str(row).strip('[]').replace('" ', "")+'\n')

  

python 之文件操作的更多相关文章

  1. Python :open文件操作,配合read()使用!

    python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...

  2. Python 常见文件操作的函数示例(转)

    转自:http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html # -*-coding:utf8 -*- ''''' Python常 ...

  3. 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容

     孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...

  4. 孤荷凌寒自学python第三十三天python的文件操作初识

     孤荷凌寒自学python第三十三天python的文件操作初识 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天开始自学python的普通 文件操作部分的内容. 一.python的文件打开 ...

  5. python中文件操作的六种模式及对文件某一行进行修改的方法

    一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...

  6. python中文件操作的其他方法

    前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r', ...

  7. Python常见文件操作的函数示例

    # -*-coding:utf8 -*- ''''' Python常见文件操作示例 os.path 模块中的路径名访问函数 分隔 basename() 去掉目录路径, 返回文件名 dirname() ...

  8. python的文件操作及简单的用例

    一.python的文件操作介绍 1.文件操作函数介绍 open() 打开一个文件 语法:open(file, mode='r', buffering=-1, encoding=None, errors ...

  9. python基本文件操作

    python文件操作 python的文件操作相对于java复杂的IO流简单了好多,只要关心文件的读和写就行了 基本的文件操作 要注意的是,当不存在某路径的文件时,w,a模式会自动新建此文件夹,当读模式 ...

  10. [转]python file文件操作--内置对象open

    python file文件操作--内置对象open   说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...

随机推荐

  1. Codeforces Round #318 (Div. 2) B Bear and Three Musketeers (暴力)

    算一下复杂度.发现可以直接暴.对于u枚举a和b,判断一下是否连边,更新答案. #include<bits/stdc++.h> using namespace std; int n,m; ; ...

  2. maven项目在myeclipse中不出现Maven Dependencies 和maven标识的解决方法

    这种情况通常出现在 我们新加载了一个 maven的项目,但是myeclipse没识别到. 或者说 我们把该项目修改成了maven项目--------也就是说该项目 有了pom.xml 但是还没有mav ...

  3. HTML网页的浏览器标题栏显示小图标的方法

    HTML网页的浏览器标题栏显示小图标的方法   就像这种效果,方法其实很简单,就是 在head头部里写: <link rel='icon' href='pic.ico ' type='image ...

  4. ios retain copy assign相关

    assign: 简单赋值,不更改索引计数copy: 建立一个索引计数为1的对象,然后释放旧对象retain:释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1 Copy其实是建立了一 ...

  5. break、continue、exit、return的区别和对比

    break.continue.exit.return的区别和对比 一:说明 break.continue在条件循环语句及循环语句(for.while.if等)中用于控制程序的走向:而exit则用于种植 ...

  6. 快照、克隆,xshell优化,Linux历史

    目录 一.虚拟拍照功能 二.虚拟机克隆功能 三.Xshell的优化 四.介绍Linux历史 一.虚拟拍照功能 1.拍摄快照 关机状态拍照 关机命令:shutdown -h now 或者 init 0 ...

  7. Python基本运算符和流程控制

    常量 常量即不可改变的量,在Python中不存在常量,我们只能逻辑上规定一个常量并不去修改它,通常用全大写字母表示. 基本运算符之二 算术运算 运算符 说明 ** 幂运算 *, /, //, % 乘. ...

  8. 基于链式链表的栈链式存储的C风格实现

    链式链表的头文件与CPP文件见前文 头文件: #ifndef _LINKSTACK_H_ #define _LINKSTACK_H_ typedef void LinkStack; //创建一个栈 L ...

  9. ubuntu 执行apt-get update报错Failed to fetch

    在ubuntu下执行sudo apt-get update时,经常会遇到报错: Err http://security.ubuntu.com precise-security InRelease Er ...

  10. 对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。 给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。

    /* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x ...