Python--文本基本操作

对文件操作流程

1. 打开文件,得到文件句柄并赋值给一个变量
2. 通过句柄对文件进行操作
3. 关闭文件


f = open('lyrics') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件

f.close() #关闭文件

打开文件的模式有:

r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件

r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Huanglinsheng

# with open('user.txt','r') as f:
#     first_line = f.readline()
#     print('first line:', first_line)
#     print('我是分隔线'.center(50, '-'))
#     data = f.read()
#     print(data)

#re.split的用法网站 https://blog.csdn.net/hawkerou/article/details/53518154

import os,re,sys
from collections import  defaultdict,OrderedDict

# with open('user.txt','r') as hls:
#     for line in hls:
#         line = line.strip('\n')
#         print(line)
#         if re.match('hls',line):
#             name = re.split(r'[\s+]',line)[0]
#             passwd = re.split(r'[\s+]', line)[1]  #默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
#             print(name,passwd)

# f = open('lock.txt',"r")
# f1 = open('user.txt',"a+")
#
# i= "hls"
#
# for line in f1:
#     if i in line:
#         i = i.replace(i,"")
#     f1.write(i)
#     f1.flush()
# f.close()
# f1.close()

'''a'''
test = open("test.txt","a")
test.write("========hls============\n")
test.close()

test1= open("test.txt","r")
print(test1.read())
test1.close()

#test1.read(15) 读取20个字符
# read())   表示读取全部内容
# readline( ) 表示逐行读取

#文件重命名
import os
os.rename("file.txt","file001.txt")

#删除文件
import os
os.remove("file001.txt")

#多行写入
#f.writelines()


#!/usr/bin/python3
#内容查找
import re
f = open('user.txt','r')
source = f.read()
f.close()
r = r'hls'
s = len(re.findall(r,source))
print(s)

#!/usr/bin/python3
#替换
import re
f1 = open('test.txt','r')
f2 = open('user.txt','r+')
for s in f1.readlines():
    f2.write(s.replace('hls','huanglinsheng'))
f1.close()
f2.close()


#实例:读取文件test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为result.txt
f = open('cdays-4-test.txt')
result = []
for line in f.readlines():                # 逐行读取数据
    line = line.strip() #去掉每行头尾空白
    if not len(line) or line.startswith('#'):   # 判断是否是空行或注释行continue     是的话,跳过不处理
        result.append(line)              #保存
result.sort()                       #排序结果
print (result)
open('cdays-4-result.txt','w').write('%s' % '\n'.join(result))        #保存入结果文件

 







posted on 2018-07-25 15:29  huanglinsheng  阅读(250)  评论(0编辑  收藏  举报

导航